## Binary numbers

February 28, 2013 Coded in C

The C language doesn't handle binary numbers directly but macros can do the job.  These macros allow bytes, halfwords, words, and longs to be specified in binary.  One warning though.  A 64 bit binary number will take up more than an 80 column line!

``````// The following macros build values in binary.  Nybbles are separated by
// commas for readability.  If a non-binary digit is used, a compiler error
// will result.  Here are some examples of the usage of the binary macros:
//
//    B4 (0110) = 0x06
//    B8 (0101,0101) = 0x55
//    B16 (1010,1010, 0101,0101) = 0xAA55
//    B32 (1000,0000, 1111,1111, 1010,1010, 0101,0101) = 0x80FFAA55
//
// For maximum readability, the bytes should be separated by spaces and there
// should be no spaces between nybbles, as shown above.  Note that an enum
// isn't used because MISRA-C generates errors otherwise.

#define b0000   0u
#define b0001   1u
#define b0010   2u
#define b0011   3u
#define b0100   4u
#define b0101   5u
#define b0110   6u
#define b0111   7u
#define b1000   8u
#define b1001   9u
#define b1010  10u
#define b1011  11u
#define b1100  12u
#define b1101  13u
#define b1110  14u
#define b1111  15u

#pragma diag_suppress = Pm120
#define B4(n0)                (b##n0)  //!< Build a nybble in binary
#pragma diag_default = Pm120

#define B8(n1, n0)            ((B4 (n1) << 4u) | B4 (n0))
//!< Build a byte in binary

#define B16(n3, n2, n1, n0)                                                   \
((B4 (n3) << 12) | (B4 (n2) << 8) | (B4 (n1) << 4) | B4 (n0))
//!< Build a halfword in binary

#define B32(n7, n6, n5, n4, n3, n2, n1, n0)                                   \
((B4 (n7) << 28) | (B4 (n6) << 24) | (B4 (n5) << 20) | (B4 (n5) << 16) \
| (B4 (n3) << 12) | (B4 (n2) <<  8) | (B4 (n1) <<  4) | B4 (n0))
//!< Build a word in binary

#define B64(nF, nE, nD, nC, nB, nA, n9, n8, n7, n6, n5, n4, n3, n2, n1, n0)   \
((B4 (nF) << 60) | (B4 (nE) << 56) | (B4 (nD) << 52) | (B4 (nC) << 48) \
| (B4 (nB) << 44) | (B4 (nA) << 40) | (B4 (n9) << 36) | (B4 (n8) << 32) \
| (B4 (n7) << 28) | (B4 (n6) << 24) | (B4 (n5) << 20) | (B4 (n5) << 16) \
| (B4 (n3) << 12) | (B4 (n2) <<  8) | (B4 (n1) <<  4) |  B4 (n0))
//!< Build a long in binary``````