1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <limits>
template < typename T >
std::string to_binary( const T& value ){
// Masques pour 8 bits.
static unsigned char flags[] = {
0x01, //00000001
0x02, //00000010
0x04, //00000100
0x08, //...
0x10,
0x20,
0x40,
0x80
} ;
const unsigned char* buffer = reinterpret_cast< const unsigned char* >( &value ) ;
// pour chaque octet, on applique les masques
std::ostringstream oss ;
for ( int i = 0; i < sizeof(value); i++ ){
for ( int j = 0; j < 8; j++ ){
oss << ( ( buffer[i] & flags[j] ) ? 1 : 0 ) ;
}
}
std::string result = oss.str() ;
std::reverse( result.begin(), result.end() );
return result ;
}
int main( int argc, char* argv[] ){
std::cout << to_binary( 12.0f ) << std::endl ;
std::cout << to_binary( 12.0 ) << std::endl ;
std::cout << to_binary( -4 ) << std::endl ;
std::cout << to_binary( 4 ) << std::endl ;
return 0 ;
} |
Partager