Oct 31, 2016

printBits() prints formatted binary numbers, Arduino code


When diagnosing embedded code, it's often convenient to see the individual bits of a variable. There is no formatting function for this in C. Wiring does have an option to format as BIN, but I wanted to see leading zeros and separate long numbers with spaces.

Here is a routine to print an integer variable in a formatted binary format including leading 0s. 
Would work with C/C++ if print command is changed appropriately.


// prints N-bit integer in this form: 0000 0000 0000 0000
// works for 4 - 32 bits
// accepts signed numbers
void printBits(long int n) {
  byte numBits = 16;  // 2^numBits must be big enough to include the number n
  char b;
  char c = ' ';   // delimiter character
  for (byte i = 0; i < numBits; i++) {
    // shift 1 and mask to identify each bit value
    b = (n & (1 << (numBits - 1 - i))) > 0 ? '1' : '0'; // slightly faster to print chars than ints (saves conversion)
    Serial.print(b);
    if (i < (numBits - 1) && ((numBits-i - 1) % 4 == 0 )) Serial.print(c); // print a separator at every 4 bits
  }
}


(latest at gitHub.)   

Example usage with the number of bits set to 16.

 printBits(0x51f);   0000 0101 0001 1111

 printBits(-1);      1111 1111 1111 1111

 int k = 65;
 printBits(k);       0000 0000 0100 0001
 

Example with the number of bits set to 10 and delimiter set to a period.

printBits(0x2A5);           10.1010.0101


A nicely implemented conversion calculator is here. http://www.binaryconvert.com/

Additional solutions are at stackoverflow.com

  

No comments: