A few months ago, I picked up a very useful function for outputting a binary string onto the screen.
This time, I wanted to make it a template function because I thought it would be neat, and because I wouldn't have to define a different function for each argument type:Code:void bits_uint(int value) { int bit; for ( bit = (~0U >> 1) + 1; bit > 0; bit >>= 1 ) { cout << (value & bit ? '1' : '0'); } cout << endl; }
When I tried implementing the function as one of typeCode:template<class T> void bits_uint(T value) { T bit; for ( bit = /* msb */(~0 >> 1) + 1; bit > 0; bit >>= 1 ) { cout << (value & bit ? '1' : '0'); } cout << endl; }
it did nothing because the bit was assigned a 0. My guess is, this happens because Intel CPUs are little endian, and the most significant bit is actually the 32nd and not the 8th as one would expect in a character.Code:bit_uint<unsigned char>(whatever)
Would there be a way to create a function which could print the binary string for any native type in c++? For example, float, double, char, etc.?