Reputation: 361
I am trying to make a hamming code decoder and encoder in C and I cannot find a way to set the bits of a variable individually.
For example, I am trying to somehow do the following:
#include "stdio.h"
int main () {
short block = 0010101110001110; // variable to contain the bits to decode
}
Clearly this will not work but I am wondering if there is a way to do this or will I have to define it as the actual number this represents?
Upvotes: 0
Views: 71
Reputation: 153547
The next version of C C2x is expected to support binary constants like 0b0010101110001110
.
For now, consider hexadecimal constants or perhaps a macro.
Tip: typically such code works best with unsigned types.
#define BIN16U(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p) ( \
((unsigned)(a)<<15) | ((b)<<14) | ((c)<<13) | ((d)<<12) | \
((e)<<11) | ((f)<<10) | ((g)<< 9) | ((h)<< 8) | \
((i)<< 7) | ((j)<< 6) | ((k)<< 5) | ((l)<< 4) | \
((m)<< 3) | ((n)<< 2) | ((o)<< 1) | ((p)<< 0))
unsigned short block = BIN16U(0,0,1,0, 1,0,1,1, 1,0,0,0, 1,1,1,0);
Upvotes: 1
Reputation: 224082
You can use hexadecimal representation, where each digit represents exactly 4 bits.
unsigned short block = 0x2b8e;
Upvotes: 1