Serial.print(X,BIN); with eight characters

Hello!

I have a short and perhaps very easy (newbie) question. When I use the function "Serial.print(X,BIN);" to get the value of the variable X as a binary number how can i ensure that i become eight characters?

Serial.print(b, BIN) prints b as a binary number in an ASCII string. For example,

int b = 79;
Serial.print(b, BIN);

prints the string "1001111".

If X has the value "6" i become "110" but i need eight characters "00000110".
Thanks for help

Hello!

I have a short and perhaps very easy (newbie) question. When I use the function "Serial.print(X,BIN);" to get the value of the variable X as a binary number how can i ensure that i become eight characters?

Serial.print(b, BIN) prints b as a binary number in an ASCII string. For example,

int b = 79;
Serial.print(b, BIN);

prints the string "1001111".

If X has the value "6" i become "110" but i need eight characters "00000110".
Thanks for help

This is a bit hokey, but should work ok (beware: untested):

<import math.h>
int zero_count = 8 - ceilf(logf((float) b) / logf(2.0));   // Conversion to base 10 log (b is decimal)
for (int i = 0; i < zero_count; ++i) {
  Serial.print('0');
} 
Serial.print(b, BIN);

of course, if b > 255, you'll have to perform some more trickery.. Here's a general solution that handles 32-bit values:

#include <math.h>

// value: What will be printed
// bits: Max number of bits to display (8 for a byte, 32 for a long etc)
void PrintBinary(long value, int bits)
{
    int zero_count = bits - ceilf(logf((float) value) / logf(2.0));
    for (int i = 0; i < zero_count; ++i)
        Serial.print('0');
    Serial.print(value, BIN);
}

Corrected for the off-by-one:

void PrintBinary(long value, int bits)
{
    float num_bits = logf(value) / logf(2.0);
    int zeros = bits - ceilf(num_bits);
    if (num_bits - (int) num_bits == 0)
        zeros--;
    for (int i = 0; i < zeros; ++i)
        Serial.print('0');
    Serial.print(value, BIN);
}