简体   繁体   中英

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. 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; 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. 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 .
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:

#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:

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

so to convert this to an int you can do this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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