1

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?

Zahra19977
  • 355
  • 1
  • 12
  • 3
    You are returning a pointer to a local variable, which is wrong because the variable will no longer exist. Please see [Function returning address of local variable error in C](https://stackoverflow.com/questions/22288871/function-returning-address-of-local-variable-error-in-c). Anyway, it seems overly complicated to stop extracting bits when the value is `0` and then fill out to 8 characters, and then reverse it. Just make the loop extract 8 bits and place them in the correct position in the output string. – Weather Vane Oct 14 '19 at 13:09
  • 2
    [`for (int i = 0; i < 8; i++) dst[i] = !!(val & (1 << (7 - i))) + '0';`](https://ideone.com/owmTCx) – pmg Oct 14 '19 at 13:15
  • 2
    Not your problem, but as a side note: There is no reason to sprinkle that magic number 48 throughout your code. Use the constant `'0'` instead. – Steve Summit Oct 14 '19 at 13:15
  • @Weather Vane Thank you so much. it solved – Zahra19977 Oct 14 '19 at 13:38
  • 1
    Regardless of local arrays, this solution is far too complex and over-engineered (and therefore very slow). You just need something like this: `void bin_str (char str[BITS+1], uint8_t n) { for(size_t i=0; i – Lundin Oct 14 '19 at 13:45

0 Answers0