I want to convert value of unsigned char to a 8 bits string that represents the number in base 2. For example i want 32
to become "00100000"
.I have written this :
char* ToStr( unsigned char ch){
char t[9] , res[9];
int num=ch , j=0 , i=0 ;
for( ; num > 0 ; i++ ){
t[i] = (num%2) + 48 ;
num= num/2 ;
}
t[i]='\0';
if( i < 8 ){//length smaller than 8
for( ; j < 8-i ; j++ )
res[j]=48;//fill it with 0 character
}
for( int i=strlen(t)-1 ; i>=0 ; i-- , j++){
res[j] = t[i];
}
res[j]='\0';
return res;
}
But it does not work and i get value 4294941796
when i try this :
int strToNum( char* s, int len){
int sum=0;
for(int i=len-1 , j=1 ; i>=0 ; i-- , j=j*2 ){
sum+= (s[i] - 48 ) * j;
}
return sum;
}
unsigned char a[2];
a[0]=32;
CString m;
m.Format( _T("num = %u "), strToNum(ToStr(a[0]) , 8) );
MessageBox(NULL,m , _T("Number"), MB_OKCANCEL);
I expected to get value 32
. What is wrong and how can i fix it?