We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
Hello, I just want to code a binary data in C. I mean hera representation is "0x5F", the decimal representation is simply "156" but what is the decimal representation. I tried 0b010010101 but it doesn't work Many thanks Sébastien
C doesn't support binary numerical constants (see K&R). Perhaps a simple macro could help: #define BIN(b7,b6,b5,b4,b3,b2,b1,b0) ((b0)+((b1)<<1)+((b2)<<2)+((b3)<<3)+((b4)<<4)+((b5)<<5)+((b6)<<6)+((b7)<<7)) Then your constant would look like this: int i = BIN(1,0,0,1,0,1,0,1); Of course, you can extend the macro to suport a greater number of bits. Regards, Mike.
The ANSI 'C' language does have a binary data notation. I suppose you could do something with the preprocessor if it's really important to you; eg,
#define B_0000_0000 0x00 #define B_0000_0001 0x01 #define B_0000_0010 0x02 #define B_0000_0011 0x03 #define B_0000_0100 0x04 etc #define B_1111_1101 0xfd #define B_1111_1110 0xfe #define B_1111_1111 0xff
#define LongToBin(n) \ (\ ((n >> 21) & 0x80) | \ ((n >> 18) & 0x40) | \ ((n >> 15) & 0x20) | \ ((n >> 12) & 0x10) | \ ((n >> 9) & 0x08) | \ ((n >> 6) & 0x04) | \ ((n >> 3) & 0x02) | \ ((n ) & 0x01) \ ) #define Bin(n) LongToBin(0x##n##l)
A very elegant macro! Has its limitations, though (max. number of bits). But the idea is great.
Nice idea. By the way <pre> and </pre> need to be lower case.
When I said, "The ANSI 'C' language does have a binary data notation" what I meant was, of course, "The ANSI 'C' language does not have a binary data notation"