Skip to content

Instantly share code, notes, and snippets.

@praisethemoon
Last active May 2, 2017 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save praisethemoon/3aff9e8277cf30ff496391c09448343c to your computer and use it in GitHub Desktop.
Save praisethemoon/3aff9e8277cf30ff496391c09448343c to your computer and use it in GitHub Desktop.
Convert Integer to binary
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#define bin(name, t) void name(t n, uint8_t* dest) { \
size_t size = sizeof(t) * 8;\
t counter = 0;\
while(n){\
if(n & 1) \
dest[counter] = '1';\
else \
dest[counter] = '0';\
n >>= 1;\
counter++;\
}\
}
bin(uint8_Bin, uint8_t)
bin(uint16_Bin, uint16_t)
bin(uint32_Bin, uint32_t)
bin(uint64_Bin, uint64_t)
int main(int argc, char* argv[]) {
uint16_t x = -1;
uint8_t dest[513] = {'\0'};
uint16_Bin(x, dest);
printf("%s\n", dest);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment