Created
February 25, 2016 17:28
-
-
Save justbuchanan/0d1fd6dd3e38e639dbb8 to your computer and use it in GitHub Desktop.
Get the binary representation of integral types in C++ as strings
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 <string> | |
template<typename TYPE, char BYTE_SEPARATOR = ' '> | |
std::string toBinary(TYPE val) { | |
std::string str("b"); | |
for (int i = sizeof(TYPE)*8-1; i >= 0; i--) { | |
str += ((val & 1 << i) ? "1" : "0"); | |
if (i % 8 == 0 && i !=0 ) str += BYTE_SEPARATOR; | |
} | |
return str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment