Friday, July 31, 2009
A Nifty Macro Trick that allows us to get Compile-Time Constants with Binary Representation…
A Nifty Macro Trick that allows us to get Compile-Time Constants
with Binary Representation…
Here’s a very handy Macro trick that uses the (##) macro
concatenation operator to generate constants from binary
representation at compile time.
#define HEX_DIGIT_0000 0
#define HEX_DIGIT_0001 1
#define HEX_DIGIT_0010 2
#define HEX_DIGIT_0011 3
#define HEX_DIGIT_0100 4
#define HEX_DIGIT_0101 5
#define HEX_DIGIT_0110 6
#define HEX_DIGIT_0111 7
#define HEX_DIGIT_1000 8
#define HEX_DIGIT_1001 9
#define HEX_DIGIT_1010 A
#define HEX_DIGIT_1011 B
#define HEX_DIGIT_1100 C
#define HEX_DIGIT_1101 D
#define HEX_DIGIT_1110 E
#define HEX_DIGIT_1111 F
#define HEX_DIGIT(a) HEX_DIGIT_ ## a
#define BINARY1H(a) (0x ## a)
#define BINARY1I(a) BINARY1H(a)
#define BINARY1(a) BINARY1I(HEX_DIGIT(a))
#define BINARY2H(a,b) (0x ## a ## b)
#define BINARY2I(a,b) BINARY2H(a,b)
#define BINARY2(a,b) BINARY2I(HEX_DIGIT(a), HEX_DIGIT(b))
#define BINARY8H(a,b,c,d,e,f,g,h) (0x##a##b##c##d##e##f##g##h)
#define BINARY8I(a,b,c,d,e,f,g,h) BINARY8H(a,b,c,d,e,f,g,h)
#define BINARY8(a,b,c,d,e,f,g,h) BINARY8I(HEX_DIGIT(a), HEX_DIGIT(b), \
HEX_DIGIT(c), HEX_DIGIT(d), HEX_DIGIT(e), HEX_DIGIT(f), \
HEX_DIGIT(g), HEX_DIGIT(h))
int main ()
{
unsigned int nibble = 0;//a nibble is a half of a byte and contains 4 bits
nibble = BINARY1(0011);
nibble = BINARY1(1010);
unsigned int Byte = 0;
Byte = BINARY2(1111, 1111);
Byte = BINARY2(0010 , 1010);
unsigned int DoubleWord = 0;
DoubleWord = BINARY8(1111, 1111, 1111, 1111, 1111, 1111, 1111, 1111);
DoubleWord = BINARY8(0000, 1111, 1010, 0001, 1111, 1111, 0100, 1000);
}
Resources:
Game Programming Gems 3.
Enjoy :)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment