Skip to content

Instantly share code, notes, and snippets.

@justbuchanan
Created February 25, 2016 17:28
Show Gist options
  • Save justbuchanan/0d1fd6dd3e38e639dbb8 to your computer and use it in GitHub Desktop.
Save justbuchanan/0d1fd6dd3e38e639dbb8 to your computer and use it in GitHub Desktop.
Get the binary representation of integral types in C++ as strings
#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