Created
December 9, 2012 13:56
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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