Skip to content

Instantly share code, notes, and snippets.

@kentkost
Last active April 6, 2018 12:51
Show Gist options
  • Select an option

  • Save kentkost/5b4b6f9b1fd41dfa1fd333d350497e3f to your computer and use it in GitHub Desktop.

Select an option

Save kentkost/5b4b6f9b1fd41dfa1fd333d350497e3f to your computer and use it in GitHub Desktop.
Universal datatype to binary representation #binary
#include <iostream>
#include <string>
#include <bitset>
#include <sstream>
#include <array>
using byte = unsigned char; //Char is the smallest possible datatype. hence the reason for using it
std::bitset<8> charToBits(byte b);
template<typename T> std::bitset<sizeof(T)*8> toBinary(const T& object);
template<typename T> std::bitset<sizeof(T)*8> toBinary(const T& object)
{
//Convert T to byte array.
std::array<byte, sizeof(T)> bytes;
const byte* begin = reinterpret_cast<const byte*>(std::addressof(object)); //start of array
const byte* end = begin + sizeof(T); //end
std::copy(begin, end, std::begin(bytes));
std::bitset<sizeof(T)*8> bits;
int pos = 0;
//magic
for(byte b : bytes)
{
std::bitset<8> temp = charToBits(b);
for(int i=0;i <8; i++){
bits.set(pos,temp[i]);
pos++;
}
}
return bits;
}
std::bitset<8> charToBits(byte b)
{
return std::bitset<8>(b);
}
int main(int argv, char* argc)
{
int x =10;
std::stringstream buffer;
buffer << toBinary(x).to_string();
std::cout<<buffer.str()<<std::endl;
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment