3

如何从字符串十六进制中获取十进制:
我有unsigned char* hexBuffer = "eb89f0a36e463d";. 并且我有我从前两个字符unsigned char* hex[5] ={'\\','x'};.
复制到. 现在我有字符串或内部十六进制。 众所周知,它是十六进制的,我们可以转换为十进制。 hexBuffer"eb"hex[2] = 'e'; hex[3] = 'b';
"\xeb""\xEB"
0xEB235

我怎样才能转换"\xEB"235(int)

(感谢jedwards
我的回答(也许对某人有用):

/*only for lower case & digits*/ 
unsigned char hash[57] ="e1b026972ba2c787780a243e0a80ec8299e14d9d92b3ce24358b1f04";  
unsigned char chr =0;  
int dec[28] ={0}; int i = 0;int c =0;  
while( *hash )  
{  
c++;  
(*hash >= 0x30 && *hash <= 0x39) ? ( chr = *hash - 0x30) : ( chr = *hash - 0x61 + 10);  
*hash++;  
if ( c == 1) dec[i] = chr * 16; else{ dec[i] += chr; c = 0; dec[i++];}  
}
4

3 回答 3

8

你想要的函数被调用sscanf.

http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/

int integer;
sscanf(hexBuffer, "%x", &integer);
于 2012-05-20T03:36:27.390 回答
5

在 C++11 中,您可以使用字符串之一到无符号整数类型整数转换函数

long i = std::stol("ff", nullptr, 16); // convert base 16 string. Accepts 0x prefix.

当然,这要求您的字符串表示一个可以适合表达式 LHS 上的整数类型的数字。

于 2012-05-20T08:11:20.093 回答
4

通常,我看到 hex2dec 函数的自制实现如下所示:

#include <stdio.h>

unsigned char hex2dec_nibble(unsigned char n)
{
    // Numbers
    if(n >= 0x30 && n <= 0x39)
    {
        return (n-0x30);
    }
    // Upper case
    else if(n >= 0x41 && n <= 0x46)
    {
        return (n-0x41+10);
    }
    // Lower case
    else if(n >= 0x61 && n <= 0x66)
    {
        return (n-0x61+10);
    }
    else
    {
        return -1;
    }    
}


int main()
{   
    unsigned char t;
    t = '0';  printf("%c = %d\n", t, hex2dec_nibble(t));
    t = 'A';  printf("%c = %d\n", t, hex2dec_nibble(t));
    t = 'F';  printf("%c = %d\n", t, hex2dec_nibble(t));
    t = 'G';  printf("%c = %d\n", t, hex2dec_nibble(t));
    t = 'a';  printf("%c = %d\n", t, hex2dec_nibble(t));
    t = 'f';  printf("%c = %d\n", t, hex2dec_nibble(t));
    t = 'g';  printf("%c = %d\n", t, hex2dec_nibble(t));
    t = '=';  printf("%c = %d\n", t, hex2dec_nibble(t));
}

其中显示:

0 = 0
A = 10
F = 15
G = 255
a = 10
f = 15
g = 255
= = 255

我将把它作为练习留给你,让你从半字节到字节,然后从字节到任意长度的字符串。

注意:我只用#includeandprintf来演示函数的hex2dec_nibble功能。没有必要使用这些。

于 2012-05-20T04:04:04.267 回答