Skip to content

Instantly share code, notes, and snippets.

@61131
Last active April 14, 2020 22:51
Show Gist options
  • Save 61131/009961b781f387ed1474ffaf19e37585 to your computer and use it in GitHub Desktop.
Save 61131/009961b781f387ed1474ffaf19e37585 to your computer and use it in GitHub Desktop.
C pre-processor macro to support binary notation within source
#ifndef _BINNOT_H
#define _BITNOT_H
#include <stdint.h>
/*
This macro provides the ability to use binary notation within C source. For
example - _B(10000001) = 129
*/
#define _B16(n) \
((uint16_t)(((((0x##n##LU) & 0x000000000000000FLU) != 0) ? (1<<0) : 0) \
+ ((((0x##n##LU) & 0x00000000000000F0LU) != 0) ? (1<<1) : 0) \
+ ((((0x##n##LU) & 0x0000000000000F00LU) != 0) ? (1<<2) : 0) \
+ ((((0x##n##LU) & 0x000000000000F000LU) != 0) ? (1<<3) : 0) \
+ ((((0x##n##LU) & 0x00000000000F0000LU) != 0) ? (1<<4) : 0) \
+ ((((0x##n##LU) & 0x0000000000F00000LU) != 0) ? (1<<5) : 0) \
+ ((((0x##n##LU) & 0x000000000F000000LU) != 0) ? (1<<6) : 0) \
+ ((((0x##n##LU) & 0x00000000F0000000LU) != 0) ? (1<<7) : 0) \
+ ((((0x##n##LU) & 0x0000000F00000000LU) != 0) ? (1<<8) : 0) \
+ ((((0x##n##LU) & 0x000000F000000000LU) != 0) ? (1<<9) : 0) \
+ ((((0x##n##LU) & 0x00000F0000000000LU) != 0) ? (1<<10) : 0) \
+ ((((0x##n##LU) & 0x0000F00000000000LU) != 0) ? (1<<11) : 0) \
+ ((((0x##n##LU) & 0x000F000000000000LU) != 0) ? (1<<12) : 0) \
+ ((((0x##n##LU) & 0x00F0000000000000LU) != 0) ? (1<<13) : 0) \
+ ((((0x##n##LU) & 0x0F00000000000000LU) != 0) ? (1<<14) : 0) \
+ ((((0x##n##LU) & 0xF000000000000000LU) != 0) ? (1<<15) : 0)))
#define _B(n) _B16(n)
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment