简体   繁体   中英

How can I store a series of bits in a variable using C language

How can I store this series of bits "000001111110001" (15bits) in a variable using C language.

I tried to store it into unsigned int:

unsigned int key=000001111110001;

but it doesn't, so please help me.

Usually, the bits are broken down into 4 bits at a time, and then converted to hexadecimal representation:

unsigned int key = 0x03F1;

You can choose to break the bits down into 3 bits at a time and use octal representation ( 01761 ), or use regular decimal representation ( 1009 ).

If you want to use bits, you can build it up yourself like this:

unsigned int key = (1<<9)|(1<<8)|(1<<7)|(1<<6)|(1<<5)|(1<<4)|(1<<0);

Or, perhaps slightly more mnemonic:

#define b4(x) \
    ((((0##x >> 9) & 01) << 3) | \
     (((0##x >> 6) & 01) << 2) | \
     (((0##x >> 3) & 01) << 1) | \
     (((0##x >> 0) & 01) << 0))
#define b8(x1, x0) ((b4(x1) << 4) | b4(x0))
#define b16(x3, x2, x1, x0) ((b8(x3, x2) << 8) | b8(x1, x0))

unsigned int key = b16(0000,0011,1111,0001);

The macro b4(x) expects x to be 4 binary digits as input, and converts it into a 12 bit octal number (that is 3 bits is used to represent a single binary digit). Then, it converts that 12 bit octal number into a true 4 bit number. b8(a,b) , and b16(a,b,c,d) extend on b4(x) .

Fancier macro tricks may help you do it in an even more automated way. See for example P99 .

If your compiler supports it (see FDinoff comment), you can represent an integer value in binary format if you precede it with a 0b :

unsigned int x = 0b000001111110001;

Some alternatives:

  • 000001111110001 is 1009 for ten-fingered humans, so just represent this value:

unsigned int x = 1009;

  • 000001111110001 is 3F1 in hexadecimal, use 0x prefix:

unsigned int x = 0x3F1;

  • If you want things more complicated, represent it in octal form, use 0 prefix:

unsigned int x = 01761;

The thing is that no matter how you represent 1009 (000001111110001, 3F1, 1761), always the same bits will go in those sizeof(unsigned int) bytes (at least for the same endianness).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM