将十六进制字符串(char[])转换为int?

时间:2022-04-03 15:45:34

I have a char[] that contains a value such as "0x1800785" but the function I want to give the value to requires an int, how can I convert this to an int? I have searched around but cannot find an answer. Thanks.

我有一个char[],它包含一个值,比如“0x1800785”,但是我想要给值的函数需要一个int,我怎么才能把它转换成int呢?我四处寻找,却找不到答案。谢谢。

9 个解决方案

#1


163  

Have you tried strtol()?

你有试过strtol()?

strtol - convert string to a long integer

将字符串转换成一个长整数。

Example:

例子:

const char *hexstring = "abcdef0";
int number = (int)strtol(hexstring, NULL, 16);

In case the string representation of the number begins with a 0x prefix, one must should use 0 as base:

如果数字的字符串表示以0x开头,那么必须以0作为基数:

const char *hexstring = "0xabcdef0";
int number = (int)strtol(hexstring, NULL, 0);

(It's as well possible to specify an explicit base such as 16, but I wouldn't recommend introducing redundancy.)

(还可以指定一个明确的基数,比如16,但我不建议引入冗余。)

#2


18  

Something like this could be useful:

类似这样的东西很有用:

char str[] = "0x1800785";
int num;

sscanf(str, "%x", &num);
printf("0x%x %i\n", num, num); 

Read man sscanf

读人sscanf

#3


9  

Assuming you mean it's a string, how about strtol?

假设你的意思是它是一根弦,那斯特尔托呢?

#4


5  

Or if you want to have your own implementation, I wrote this quick function as an example:

或者,如果你想有你自己的实现,我写了这个快速函数为例:

/**
 * hex2int
 * take a hex string and convert it to a 32bit number (max 8 hex digits)
 */
uint32_t hex2int(char *hex) {
    uint32_t val = 0;
    while (*hex) {
        // get current character then increment
        uint8_t byte = *hex++; 
        // transform hex character to the 4bit equivalent number, using the ascii table indexes
        if (byte >= '0' && byte <= '9') byte = byte - '0';
        else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
        else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;    
        // shift 4 to make space for new digit, and add the 4 bits of the new digit 
        val = (val << 4) | (byte & 0xF);
    }
    return val;
}

#5


3  

Try below block of code, its working for me.

试试下面的代码块,它为我工作。

char *p = "0x820";
uint16_t intVal;
sscanf(p, "%x", &intVal);

printf("value x: %x - %d", intVal, intVal);

Output is:

输出是:

value x: 820 - 2080

#6


2  

So, after a while of searching, and finding out that strtol is quite slow, I've coded my own function. It only works for uppercase on letters, but adding lowercase functionality ain't a problem.

因此,经过一段时间的搜索,发现strtol是相当慢的,我编写了自己的函数。它只适用于大写字母,但添加小写功能不成问题。

int hexToInt(PCHAR _hex, int offset = 0, int size = 6)
{
    int _result = 0;
    DWORD _resultPtr = reinterpret_cast<DWORD>(&_result);
    for(int i=0;i<size;i+=2)
    {
        int _multiplierFirstValue = 0, _addonSecondValue = 0;

        char _firstChar = _hex[offset + i];
        if(_firstChar >= 0x30 && _firstChar <= 0x39)
            _multiplierFirstValue = _firstChar - 0x30;
        else if(_firstChar >= 0x41 && _firstChar <= 0x46)
            _multiplierFirstValue = 10 + (_firstChar - 0x41);

        char _secndChar = _hex[offset + i + 1];
        if(_secndChar >= 0x30 && _secndChar <= 0x39)
            _addonSecondValue = _secndChar - 0x30;
        else if(_secndChar >= 0x41 && _secndChar <= 0x46)
            _addonSecondValue = 10 + (_secndChar - 0x41);

        *(BYTE *)(_resultPtr + (size / 2) - (i / 2) - 1) = (BYTE)(_multiplierFirstValue * 16 + _addonSecondValue);
    }
    return _result;
}

Usage:

用法:

char *someHex = "#CCFF00FF";
int hexDevalue = hexToInt(someHex, 1, 8);

1 because the hex we want to convert starts at offset 1, and 8 because it's the hex length.

因为我们想要转换的十六进制从1开始,8因为它是十六进制长度。

Speedtest (1.000.000 calls):

公司创收Speedtest(电话):

strtol ~ 0.4400s
hexToInt ~ 0.1100s

#7


1  

i have done a similar thing, think it might help u its actually working for me

我也做过类似的事情,我想它可能会帮助你为我工作。

int main(){ int co[8],i;char ch[8];printf("please enter the string:");scanf("%s",ch);for(i=0;i<=7;i++){if((ch[i]>='A')&&(ch[i]<='F')){co[i]=(unsigned int)ch[i]-'A'+10;}else if((ch[i]>='0')&&(ch[i]<='9')){co[i]=(unsigned int)ch[i]-'0'+0;}}

here i have only taken a string of 8 characters. if u want u can add similar logic for 'a' to 'f' to give their equivalent hex values,i haven't done that cause i didn't needed it.

这里我只选取了8个字符。如果你想让你在“a”和“f”之间添加相似的逻辑来给出它们等价的十六进制值,我还没有做,因为我不需要它。

#8


0  

I made a librairy to make Hexadecimal / Decimal conversion without the use of stdio.h. Very simple to use :

我做了一个librairy做十六进制/十进制转换而不使用stdio.h。使用非常简单:

unsigned hexdec (const char *hex, const int s_hex);

Before the first conversion intialize the array used for conversion with :

在第一次转换之前,用于转换的阵列:

void init_hexdec ();

Here the link on github : https://github.com/kevmuret/libhex/

这里是github上的链接:https://github.com/kevmuret/libhex/。

#9


0  

Use xtoi ( stdlib.h ). The string has "0x" as first two indexes so trim val[0] and val[1] off by sending xtoi &val[2].

使用xtoi(stdlib。h)。该字符串有“0x”作为前两个索引,通过发送xtoi &val[2]将val[0]和val[1]去掉。

xtoi( &val[2] );

xtoi(val[2]);

#1


163  

Have you tried strtol()?

你有试过strtol()?

strtol - convert string to a long integer

将字符串转换成一个长整数。

Example:

例子:

const char *hexstring = "abcdef0";
int number = (int)strtol(hexstring, NULL, 16);

In case the string representation of the number begins with a 0x prefix, one must should use 0 as base:

如果数字的字符串表示以0x开头,那么必须以0作为基数:

const char *hexstring = "0xabcdef0";
int number = (int)strtol(hexstring, NULL, 0);

(It's as well possible to specify an explicit base such as 16, but I wouldn't recommend introducing redundancy.)

(还可以指定一个明确的基数,比如16,但我不建议引入冗余。)

#2


18  

Something like this could be useful:

类似这样的东西很有用:

char str[] = "0x1800785";
int num;

sscanf(str, "%x", &num);
printf("0x%x %i\n", num, num); 

Read man sscanf

读人sscanf

#3


9  

Assuming you mean it's a string, how about strtol?

假设你的意思是它是一根弦,那斯特尔托呢?

#4


5  

Or if you want to have your own implementation, I wrote this quick function as an example:

或者,如果你想有你自己的实现,我写了这个快速函数为例:

/**
 * hex2int
 * take a hex string and convert it to a 32bit number (max 8 hex digits)
 */
uint32_t hex2int(char *hex) {
    uint32_t val = 0;
    while (*hex) {
        // get current character then increment
        uint8_t byte = *hex++; 
        // transform hex character to the 4bit equivalent number, using the ascii table indexes
        if (byte >= '0' && byte <= '9') byte = byte - '0';
        else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
        else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;    
        // shift 4 to make space for new digit, and add the 4 bits of the new digit 
        val = (val << 4) | (byte & 0xF);
    }
    return val;
}

#5


3  

Try below block of code, its working for me.

试试下面的代码块,它为我工作。

char *p = "0x820";
uint16_t intVal;
sscanf(p, "%x", &intVal);

printf("value x: %x - %d", intVal, intVal);

Output is:

输出是:

value x: 820 - 2080

#6


2  

So, after a while of searching, and finding out that strtol is quite slow, I've coded my own function. It only works for uppercase on letters, but adding lowercase functionality ain't a problem.

因此,经过一段时间的搜索,发现strtol是相当慢的,我编写了自己的函数。它只适用于大写字母,但添加小写功能不成问题。

int hexToInt(PCHAR _hex, int offset = 0, int size = 6)
{
    int _result = 0;
    DWORD _resultPtr = reinterpret_cast<DWORD>(&_result);
    for(int i=0;i<size;i+=2)
    {
        int _multiplierFirstValue = 0, _addonSecondValue = 0;

        char _firstChar = _hex[offset + i];
        if(_firstChar >= 0x30 && _firstChar <= 0x39)
            _multiplierFirstValue = _firstChar - 0x30;
        else if(_firstChar >= 0x41 && _firstChar <= 0x46)
            _multiplierFirstValue = 10 + (_firstChar - 0x41);

        char _secndChar = _hex[offset + i + 1];
        if(_secndChar >= 0x30 && _secndChar <= 0x39)
            _addonSecondValue = _secndChar - 0x30;
        else if(_secndChar >= 0x41 && _secndChar <= 0x46)
            _addonSecondValue = 10 + (_secndChar - 0x41);

        *(BYTE *)(_resultPtr + (size / 2) - (i / 2) - 1) = (BYTE)(_multiplierFirstValue * 16 + _addonSecondValue);
    }
    return _result;
}

Usage:

用法:

char *someHex = "#CCFF00FF";
int hexDevalue = hexToInt(someHex, 1, 8);

1 because the hex we want to convert starts at offset 1, and 8 because it's the hex length.

因为我们想要转换的十六进制从1开始,8因为它是十六进制长度。

Speedtest (1.000.000 calls):

公司创收Speedtest(电话):

strtol ~ 0.4400s
hexToInt ~ 0.1100s

#7


1  

i have done a similar thing, think it might help u its actually working for me

我也做过类似的事情,我想它可能会帮助你为我工作。

int main(){ int co[8],i;char ch[8];printf("please enter the string:");scanf("%s",ch);for(i=0;i<=7;i++){if((ch[i]>='A')&&(ch[i]<='F')){co[i]=(unsigned int)ch[i]-'A'+10;}else if((ch[i]>='0')&&(ch[i]<='9')){co[i]=(unsigned int)ch[i]-'0'+0;}}

here i have only taken a string of 8 characters. if u want u can add similar logic for 'a' to 'f' to give their equivalent hex values,i haven't done that cause i didn't needed it.

这里我只选取了8个字符。如果你想让你在“a”和“f”之间添加相似的逻辑来给出它们等价的十六进制值,我还没有做,因为我不需要它。

#8


0  

I made a librairy to make Hexadecimal / Decimal conversion without the use of stdio.h. Very simple to use :

我做了一个librairy做十六进制/十进制转换而不使用stdio.h。使用非常简单:

unsigned hexdec (const char *hex, const int s_hex);

Before the first conversion intialize the array used for conversion with :

在第一次转换之前,用于转换的阵列:

void init_hexdec ();

Here the link on github : https://github.com/kevmuret/libhex/

这里是github上的链接:https://github.com/kevmuret/libhex/。

#9


0  

Use xtoi ( stdlib.h ). The string has "0x" as first two indexes so trim val[0] and val[1] off by sending xtoi &val[2].

使用xtoi(stdlib。h)。该字符串有“0x”作为前两个索引,通过发送xtoi &val[2]将val[0]和val[1]去掉。

xtoi( &val[2] );

xtoi(val[2]);