简体   繁体   English

将存储为字符的十六进制字符串转换为C中的十进制

[英]Converting hex string stored as chars to decimal in C

I'm given a string hex_txt containing a 4 digit hex number in the way outlined in the code, split up in two array entries. 我得到了一个字符串hex_txt,其中包含代码中概述的4位十六进制数字,并分成两个数组项。 I need to convert it to decimal. 我需要将其转换为十进制。 The following is the way I'm doing it. 以下是我的操作方式。

unsigned char hex_txt[] = "\xAB\xCD";
unsigned char hex_num[5];
unsigned int dec_num;

sprintf(hex_num, "%.2x%.2x", (int)hex_txt[0], (int)hex_txt[1]);
printf("%s\n", hex_num);
sscanf(hex_num, "%x", &dec_num);
printf("%d\n", dec_num);

Is there a faster, or more efficient way of doing this? 有没有更快或更有效的方法? This is my current ad hoc solution, but I'd like to know if there's a proper way to do it. 这是我目前的临时解决方案,但我想知道是否有适当的方法来做到这一点。

int result = (unsigned char)hex_txt[0] * 256 + (unsigned char)hex_txt[1];

The string hex_txt contains two bytes; 字符串hex_txt包含两个字节。 I'm guessing that the order is big-endian (reverse the subscripts if it is little-endian). 我猜想顺序是大端的(如果是小端的,则颠倒下标)。 The character code for hex_txt[0] is 0xAB, for hex_txt[1] is 0xCD. hex_txt[0]的字符代码为0xAB, hex_txt[1]的字符代码为0xCD。 The use of unsigned char casts ensures that you don't get messed up by signed characters. 使用无符号字符转换可确保您不会被带符号的字符弄乱。

Or, to do it all at once: 或者,一次完成所有操作:

printf("%d\n", (unsigned char)hex_txt[0] * 256 + (unsigned char)hex_txt[1]);

Simply use strtoul() function from stdlib.h . 只需使用stdlib.h strtoul()函数。
See the following example: 请参见以下示例:

const char sHex[] = "AE";

unsigned char ucByte = 0;

ucByte = (unsigned char) strtoul(sHex, NULL, 16); //BASE 16 FOR HEX VALUES

Here's what I do: 这是我的工作:

n = 0;
while (*p){
    if (ISDIGIT(*p)) n = n*16 + (*p++ - '0');
    else if (ISALPHA(*p)) n = n*16 + (LOWERCASE(*p++) - 'a' + 10);
    else break;
}

And (you'll hate this but it works for ASCII) I cheat: 而且(您会讨厌这一点,但是它适用于ASCII)我作弊:

#define LOWERCASE(c) ((c) | ' ')

ADDED: Sorry, I just re-read your question. 添加:对不起,我只是重新阅读了您的问题。 Why not do: 为什么不这样做:

(unsigned int)(unsigned char)p[0] * 256 + (unsigned int)(unsigned char)p[1]

I might be babbling but if you use: 我可能会胡言乱语,但如果您使用:

 char hex_txt[] = "\xAB\xCD";

then in effect you just define 2 bytes: 那么实际上您只需定义2个字节:

 char hex_txt[] = {0xab, 0xcd};

so to convert this to an int you can do this: 因此要将其转换为int可以执行以下操作:

 int number = (int) ((short *) *hex_text);

尽管我在这里发布了一段C ++代码,但您可能不需要它。

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

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