将包含十进制数字的字符串转换为无符号字符



我有一个包含十进制数的字符(字符串)数组。如何将其转换为无符号字符?

char  my_first_reg[2];
memcpy( my_first_reg, &my_str_mymatch[0], 1 );
my_first_reg[1] = '';
// now my_first_reg contain reg number ... how to convert to unsigned char  

要将 ASCII 字符转换为其数值my_first_reg[0]

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

这是有效的,因为 ASCII 表中的数字是连续的:

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

以上用于转换一个字符。 如果你有一个更长的字符串,请考虑使用 atoi()strtol()sscanf() 或类似的东西。

最新更新