Displaying each bit within a byte

Hi,

I have two questions.. 1) How do I display each bit within a byte, i.e. how do I display it as a series of ones and zeros? Example, the byte ‘97’ can be displayed as ‘97’ or ‘a’, but I’d like to display it as ‘01100001’. 2) Secondly, how do I manipulate individual bits within a byte? i.e. how can I determine if the (for example) 3rd bit from the left is zero or a one, and if need be, how can I change that bit alone?

Why am I asking? I’m trying to do some PDU encoding to send SMSs, I know there’s a PDU library available, but it uses lots of long Strings and seems to be quite memory hungry. I’m trying to re-write it, but it seems to involve a lot of bit and byte manipulation.

Cheers

  1. Serial.print() has a BIN option.
  2. Look at the Bits and Bytes section of the Reference page for bit manipulation functions.

how do I manipulate individual bits within a byte?

You can do it the grown up way using and and or operations. On the other hand the Arduino offers a beginners bit read, bit set and bit clear operation.

How do I display each bit within a byte,

A simple loop printing out a 1 or 0 depending on the value of the least significant bit. Then next time round the loop shift the byte to the right. Again the and operation will help you isolate the least significant bit or you could use the bit read.

Thanks guys - both answers very useful !