0

I am trying to write binary literals in a cleaner format.

I understand that the following can be done for integer literals:

int x = 1234_5678_9999;

I assumed this would work for binary literals, so I tried:

uint32_t branch_bitmask = 0b0000_1111_0000_0000_0000_0000_0000_0000;

Which gives me an "invalid suffix" error for everything past the first underscore.

Is there an alternative to underscores that would allow me to write the binary literal in a cleaner way than just:

uint32_t branch_bitmask = 0b00001111000000000000000000000000;
M S
  • 15
  • 5
  • 1
    I know in C++ there is the `'` digit separator, but I don't think there is anything similar for standard C, there may be a GCC extension but that won't be portable across all compilers – txk2048 May 30 '20 at 19:40
  • 1
    not in c programming language. the only way is to convert it to string (e.g. with itoa() function) and then insert your seperators in the output string. – Adam May 30 '20 at 19:45
  • In the end I chose to replace the binary with an integer literal and put the 'cleaner' but invalid binary literal just after (commented). – M S May 30 '20 at 21:26

1 Answers1

4

If you always have the same number of bits (32 in your example) you could #define a macro a bit like this:

#define BITS32(b1,b2,b3,b4,b5,b6,b7,b8) ( \
  ((b1) << 28) + \
  ((b2) << 24) + \
  ((b3) << 20) + \
  ((b4) << 16) + \
  ((b5) << 12) + \
  ((b6) << 8) + \
  ((b7) << 4) + \
  (b8))

and then call it like this:

uint32_t branch_bitmask = BITS32(0b0000,0b1111,0b0000,0b0000,0b0000,0b0000,0b0000,0b0000);

or you can go further and use ## in the macro to prepend the 0b.

But the simple answer for me has always been to use hexadecimal, as one hex digit is 4 bits.

uint32_t branch_bitmask = 0x0F000000;
Brecht Sanders
  • 6,215
  • 1
  • 16
  • 40