How to print all the 8 bits of a byte on serial monitor, if they are all zero

OldSteve:
I decided to do a little test.
A 'for' loop shift wins by 4 bytes of program space. Both use the same RAM.

I commented out each method in turn:-

void setup()

{
   // Common lines:-
   Serial.begin(115200);
   byte val = 16;

// 2124 program / 182 RAM:-
   for (int i = 0; i < 8; i++)
   {
       bool b = val & 0x80;
       Serial.print(b);
       val = val << 1;
   }

// or

// 2128 program / 182 RAM:-
   for (int i = 7; i >= 0; i--)
   {
       bool b = bitRead(val, i);
       Serial.print(b);
   }
}

void loop(){}

Hello!
I'm new to arduino , I want to ask beginners questions :stuck_out_tongue:

I don't understand below code, how it work?

bool b = val & 0x80;

  1. "&" mean Bitwise Operators?
  2. in case val=4...

(with"&0x80") val&0x80 = 00000100
(without"&0x80") val = 11111100

" &0x80 " how it work ?

Thanks :slight_smile:

0x80 is 0b10000000

when you use bitwise AND you get a 1 if both bits are 1, otherwise you get a 0

Using & 0x80 will ensure that all bits except the leftmost bit will be 0. The value of the leftmost bit will depend on the value at that bit position in the other number

This is a very old Thread. If you have more questions about a project you are working on it would make sense to start your own Thread (Topic) and tell us what you are trying to create.

...R