Wednesday, August 31, 2022

[SOLVED] Is there a way to do grouping in GCC binary literals?

Issue

I work with registers a bit, and data sheets that turn everything into bit indices. Luckily, I'm using GCC, which has the binary literal extension syntax so that i can do things like

register |= 0b01000010;

The other option is of course to just use hexadecimal format

register |= 0x42;

Despite having worked with hexadecimal numbers a bit over time, I still find binary format better for this kind of bit banging. I still decompose the 4 and 2 nibbles into their 0100 and 0010 patterns. So I think the binary format visualizes better. The problem with the binary format though, is that it's hard to find the boundaries. Using hexadecimal format, the nibbles separate nicely and so you can "index" bits safer sometimes. In other words, in the top I have to worry I didn't add or omit an extra 0 and end up with bit 7 on instead of 6.

Has a technique/trick been developed to have their cake and eat it too? When you have two string constants adjacent in C

"Hello " "World"

The compiler is smart enough to just mash them together into one literal. It would be nice if there was a way to do something similar with these binary numbers, e.g.,

0b0100 0010

I could do something weird with macros, perhaps

#define _(a, b) (((a) << 4) | (b))

and then be able to do

_(0b0100,0b0010)

but that's honestly worse, and limited to a pair of nibbles. Is there something clever and nice?


Solution

In C, you're limited to specifying integer constants in decimal, octal, and hexadecimal. Or combine groups of shifted constants (per H2CO3's comment below your question). If it's important enough to you, you could specify your contants as quoted string constants and call a function (of your own writing) to convert that & return its integer value. Anywhere you want to specify such a constant, just call your function in its place... int i = b("0100 1101 0011 1100"); ....Or use C++.... See Binary literals? and Can I use a binary literal in C or C++?

If you go with writing your own string constant converter, you can make it ignore non-[0,1] digits, so you can group the bits in any fashion depending on what you're specifying.



Answered By - phonetagger
Answer Checked By - Robin (WPSolving Admin)