Skip to content

Instantly share code, notes, and snippets.

@nevkontakte
Created December 9, 2012 13:56
Show Gist options
  • Save nevkontakte/4244971 to your computer and use it in GitHub Desktop.
Save nevkontakte/4244971 to your computer and use it in GitHub Desktop.
Function to generate binary representation of arbitrary numeric type. Fast. Not thread-safe.
#include <iostream>
template<typename T> char* binary(T n) {
const int bits = sizeof(T)*8;
static char str[bits+1];
str[bits] = 0;
for(int i = 0; i < bits; i++) {
str[bits-i-1] = '0' + (n & 1);
n = n >> 1;
}
return str;
}
int main() {
char c = 1 << (8*sizeof(char)-1);
std::cout << binary(c) << std::endl;
c = ((unsigned char)c) >> 1;
std::cout << binary(c) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment