0

I have an array of char (string) that contain a decimal number. How do I convert it to unsigned char?

char  my_first_reg[2];
memcpy( my_first_reg, &my_str_mymatch[0], 1 );
my_first_reg[1] = '\0';
// now my_first_reg contain reg number ... how to convert to unsigned char  
lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75
user836026
  • 10,608
  • 15
  • 73
  • 129

1 Answers1

1

To convert my_first_reg[0] the ASCII character to its numeric value:

unsigned char value = my_first_reg[0] - '0';

This works because digits in the ASCII table are sequential:

    '0' = 0x30 = 48
    '1' = 0x31 = 49
    '2' = 0x32 = 50
    '3' = 0x33 = 51
    '4' = 0x34 = 52
    ...
    '9' = 0x39 = 57

The above is for converting one character. If you have a longer string, consider using atoi(), strtol(), sscanf(), or something similar.

e0k
  • 6,961
  • 2
  • 23
  • 30