Représentation binaire d objets.
Bonjour, je cherche à créer une fonction template qui renvoie un string contenant la représentation binaire d un objet.
J'en suis arrivé à : (En commentaire une ancienne version qui engendrait des rotations)
Code:
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
| #include <string>
using namespace std;
template<class T> string binaryString(const T& O)
{
int size = sizeof(T);
static const int sizeofuchar = sizeof(unsigned char);
static const unsigned char c = static_cast<unsigned char> (1); //Avant : c = char(128)
const unsigned char* curpart = reinterpret_cast<const unsigned char*> (&O);
char cur = c;
string ret = "";
for(int i = 0; i<size ; i++)
{
for(int j=0; j<sizeofuchar*8; j++)
{
ret=(cur&(*curpart) ? "1" :"0")+ret ; //Avant : ret+=(cur&(*curpart) ? "1" :"0");
cur<<=1; //Avant cur>>=1;
}
curpart++;
ret=" "+ret; // Avant : ret+=" ";
}
return ret;
} |
seulement, quand je teste cette fonction via :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include "TPrintBinary.h"
#include <string>
#include <iostream>
using namespace std;
int main(){
string S;
const int SIZE = 10;
cout << "*******************Entiers (int) ***********************"<<endl;
int A[SIZE] = {1,2,4,8,16,32,64,128,256,512};
for (int i=0; i<SIZE; i++){
cout<< binaryString(A[i]) ;
cout<<" : " << A[i] << " : int " <<endl;
}
} |
Une idée ?
j'obtiens :
Code:
1 2 3 4 5 6 7 8 9 10
| 00000000 00000000 00000000 00000001 : 1 : int
00000000 00000000 00000000 00000010 : 2 : int
00000000 00000000 00000000 00000100 : 4 : int
00000000 00000000 00000000 00001000 : 8 : int
00000000 00000000 00000000 00010000 : 16 : int
00000000 00000000 00000000 00100000 : 32 : int
00000000 00000000 00000000 01000000 : 64 : int
00000000 00000000 00000000 10000000 : 128 : int
00000000 00000000 00000000 00000000 : 256 : int
00000000 00000000 00000000 00000000 : 512 : int |
Une idée ?