Skip to content

Instantly share code, notes, and snippets.

@dmbfm
Created August 1, 2020 15:04
Show Gist options
  • Save dmbfm/62d471fb4902b58f29e49169fb78df01 to your computer and use it in GitHub Desktop.
Save dmbfm/62d471fb4902b58f29e49169fb78df01 to your computer and use it in GitHub Desktop.
// from http://cakoose.com/wiki/c_preprocessor_abuse
#define BIN_0000 0
#define BIN_0001 1
#define BIN_0010 2
#define BIN_0011 3
#define BIN_0100 4
#define BIN_0101 5
#define BIN_0110 6
#define BIN_0111 7
#define BIN_1000 8
#define BIN_1001 9
#define BIN_1010 a
#define BIN_1011 b
#define BIN_1100 c
#define BIN_1101 d
#define BIN_1110 e
#define BIN_1111 f
#define BIN_8_HEXIFY(b1,b2) (0x ## b1 ## b2)
#define BIN_8_RELAY(b1,b2) BIN_8_HEXIFY(b1, b2)
#define BIN_8(b1,b2) BIN_8_RELAY(BIN_ ## b1, BIN_ ## b2)
#define BIN_16_HEXIFY(b1,b2,b3,b4) (0x ## b1 ## b2 ## b3 ## b4)
#define BIN_16_RELAY(b1,b2,b3,b4) BIN_16_HEXIFY(b1, b2, b3, b4)
#define BIN_16(b1,b2,b3,b4) BIN_16_RELAY(BIN_##b1, BIN_##b2, BIN_##b3, BIN_##b4)
//The reason we need those helper functions is that the preprocessor’s parameter evaluation order is strange (the GCC preprocessor manual explains it clearly).
//To use it:
BIN_16(0010,1100,1010,1111)
// Gets translated to: 0x2caf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment