 # How to Leading Zero's Serial print of Byte

Hi there
Im currently working on a project for school. I had print some byte values on the Serial Monitor with use of Serial.print(byte)

So for example: Variable Byte is made, and given value 8.
It has to be printed binairy on serial monitor, but with leading zero's
So output looks like this: 0b0001000

byte Byte = 8;

void Setup
{
Serial.begin(9600);
Serial.println(byte, BIN);
}

Any tips or stuff I could use / learn instead to do this?
Thanks!

Yes, it would be cheating to give you more than this:
https://www.arduino.cc/reference/en/language/structure/control-structure/for/

The object of the assignment is for you to think about, and then solve the problem.

jremington:
The object of the assignment is for you to think about, and then solve the problem.

... and learn to do research

You are given:

``````byte Byte = 8;   //00001000 (b7 b6 b5 b4 b3 b2 b1 b0) in base 2
``````

Remember: Any data item (8-bit/byte, 16-bit/int, 32-bit/long int, 64-bit/long long int, 32-bit/float) is always stored in a memory location(s) in bit form. So, your variable Byte will have this storage pattern in the RAM Memory of the MCU: 00001000.

You want to show all the bits on the Serial Monitor; so, follow these steps:
1. Read MSBit (Most significant bit, b7) :

``````bool n = bitRead(Byte, 7);
``````

2. Show the value of n of Step-1 onto Serial Monitor:

``````Serial.print(n, BIN);
``````

3. Repeat Step-1 and 2 for the remaining bits.
4. Now, use for() loop to reduce the number of code lines.

``````for(int i = 7; i ....; i.....)
{
.................................
.................................
}
``````

GolamMostafa:
2. Show the value of n of Step-1 onto Serial Monitor:

``````Serial.print(n, BIN);
``````

It is not necessary to specify BIN here, you can just use:

``````Serial.print(n);
``````

bitRead() only returns 0 or 1, and n is a boolean type. 1 and 0 are represented with exactly the same digits in every base.

aarg:
It is not necessary to specify BIN here, you can just use:

``````Serial.print(n);
``````

Then the default base is DEC; but, the number is binary; so, I wanted to remain technically correct by specifying the base (BIN) explicitly.