C conver unsigned char to HEX

879 views Asked by At

is convert unsigned char / int to hex, trouble is no correct translate ascci table: original: 0D, converted: AD code:

char int_to_hex(int d) {
   if (d < 0)  return -1;
   if (d > 16) return -1;
   if (d <= 9) return '0' + d;
   d -= 10;
   return (char)('A' + d);
}
void uint_to_hex(unsigned char in, char **out, int *olen) {
   int  i = 0;
   int  remain[2];
   int  result = (int)in;

   while (result) {
      remain[i++] = result % 16;
      result /= (int)16;
   }
   for (i = 1; i >= 0; --i) {
    char c = int_to_hex(remain[i]);
    if( (int)c == -1 ) { continue; }
    *((*out) + (*olen)) = (char)c; (*olen)++;
   }
}

where is incorrect ?..

1

There are 1 answers

1
4rlekin On

First of all one hex digit will cover values from 0 (0) to 15 (F) not from 0 to 16 (as you seem to assume in int_to_hex function).
Also you don't really need typecasting to char in last return of that function.
In fact all typecasts here are rather unnecessary
And typecasting of literal 16 is purely absurd...

And how sample input for uint_to_hex is looking ? You are aware, that on input (in) you can pass only single character ?

I think that char pointer would suffice for out - i mean, you want to return array, right ? So instead of ** should be only singe *.
And I don't understand why olen has to be pointer (and argument to function too).

And you should try to write more concise and readable code, it will help you understand what you are doing too.