简体   繁体   English

在 C/C++ 中将用 ASCII 字符表示的十六进制数转换为十进制整数

[英]Converting a hexadecimal number represented in ASCII characters to a decimal integer in C/C++

my problem is as follows.我的问题如下。

I'm reading a piece of ascii data from a sensor, let's say it's "400".我正在从传感器读取一段 ascii 数据,假设它是“400”。 It's stored in an array of characters.它存储在一个字符数组中。 In hex (ascii) that would be { 0x34, 0x30, 0x30 }.在十六进制 (ascii) 中,这将是 { 0x34, 0x30, 0x30 }。

What I'm trying to get from that set of characters is an integer in decimal representative of hex 0x400, which would be 1024. All the other numeric values in this array of ascii characters are represented in decimal, so I've been using this:我试图从这组字符中得到一个代表十六进制 0x400 的十进制整数,即 1024。这个 ascii 字符数组中的所有其他数值都以十进制表示,所以我一直在使用这个:

int num_from_ascii(char reading[], int start, int length){
    printf("++++++++num_from_ascii+++++++++\n");
    char radar_block[length];
    for(int i = 0; i < length; i++){
        radar_block[i] = reading[start + i];
        printf("%02x ", reading[start + i]);
    }
  printf("\n");
  return atoi(radar_block);
}

This obviously just gives me back 400, but I need a decimal integer from a hex value.这显然只是给了我 400,但我需要一个来自十六进制值的十进制整数。 Any advice?有什么建议吗?

As Eugene has suggested, all you need to do is replace atoi(radar_block) by strtol(radar_block, NULL, 16) .正如 Eugene 所建议的,您需要做的就是将atoi(radar_block)替换为strtol(radar_block, NULL, 16) That takes a "base" argument, which can be 10 for decimal, 16 for hex (which is what you want), etc or 0 to auto-detect using the C++ rules (leading "0x" for hex, leading "0" for octal).这需要一个“基数”参数,它可以是十进制的1016进制的16 (这是你想要的)等或0使用 C++ 规则自动检测(前导“0x”表示十六进制,前导“0”表示八进制)。

You should never use atoi anyway because it does not handle invalid inputs safely.无论如何你都不应该使用atoi ,因为它不能安全地处理无效输入。 strtol does everything that atoi does, has well defined errno for all edge cases, and also allows you to distinguish "0" from non-numeric input. strtol完成atoi所做的一切,为所有边缘情况定义了明确的 errno,并且还允许您将"0"与非数字输入区分开来。

As user3121023 mentioned, don't forget to NUL-terminate the string you pass to strtol (this is a serious bug in your code calling atoi as well).正如 user3121023 所提到的,不要忘记将传递给strtol的字符串以 NUL 结尾(这也是调用atoi的代码中的一个严重错误)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM