Binary and laeding zero's

Hi,

this question is bound to have been asked before but I could not find it in the search...

Is there a way to print the leading zero's of a byte?

If I try :

byte v=17; Serial.println(v,BIN);

it prints : 10001

I would like it to print : 00010001

byte aByte = 0b00010001;
void setup()
{
  Serial.begin(115200);
  printByte(aByte);
  printByte(00000001);
}

void loop()
{
}
void printByte(byte theByte)
{
  for (int bit = 7; bit >= 0; bit--)
  {
    Serial.print(bitRead(theByte, bit));
  }
  Serial.println();
}

Thanks,

I already feared a loop would be the only solution...

Kevin77:
Thanks,

I already feared a loop would be the only solution…

a template would allow you to print any size object:

template <class T> T printByte (T arg)
{
  size_t size = sizeof(arg) * 8;
  Serial.print(F("0b"));
  for (size_t i = 0; i < size; i++)
  {
    T mask = (T)1 << (size - i - 1);
    Serial.print(arg & mask? "1" : "0");
  }
  Serial.println();
}

void setup() 
{
  Serial.begin(9600);
  uint32_t my32 = 0xFF00FF00;
  uint16_t my16 = 0x01AA;
  uint8_t my8 = 0xF0;
  printByte(my32);
  printByte(my16);
  printByte(my8);
}

void loop() 
{
}

A nice challenge to do it without a loop, note this is not fast or so.
Could be made faster with help of seven if statements (but that is in fact an unrolled loop)

void printBin(uint8_t n)
{
  char zeroos[] = "00000000";
  if (n == 0)
  {
    Serial.print(zeroos);
    return;
  }
  int leadingZeros = floor(log(n)/log(2)) + 1;  //  length of a binary number > 0
  Serial.print(&zeroos[leadingZeros]);
  Serial.print(n, BIN);
}

void setup()
{
  Serial.begin(115200);
  Serial.println(__FILE__);
  
  for (int i=0; i<256; i++) 
  {
    printBin(i);
    Serial.println();
  }
  Serial.println("done...");
}

void loop() {}
// END OF FILE

There's no point avoiding the loop. If your code doesn't have a loop, then the print function has to loop through the characters.