-4

我正在尝试将十六进制从strtoul函数转换为无符号整数。但我得到的输出为ffffffff. 我用过stdlib.h图书馆。有人可以告诉我我错在哪一部分吗?

void main()
{
   char str1[33] = "88CC6069E4EDF969773369F988CC969F";
   unsigned int hex_int;
   hex_int = strtoul(str1, NULL, 16); //converting to unsigned int
   printf("%x\n", hex_int);
}
4

3 回答 3

1

C11 7.22.1.4p8

strtolstrtoll和函数返回转换strtoulstrtoull的值(如果有)。如果无法执行转换,则返回零。如果正确的值在可表示值的范围之外,LONG_MIN, LONG_MAX, LLONG_MIN, LLONG_MAX, ULONG_MAX, 或被ULLONG_MAX返回(根据返回类型和值的符号,如果有的话),宏的值ERANGE存储在errno.

试试下面的代码:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char str1[] = "88CC6069E4EDF969773369F988CC969F";
    errno = 0; // must reset errno first, otherwise it can retain an old value
    unsigned long int hex_int = strtoul(str1, NULL, 16); 
    if (errno != 0) {
        perror("strtoul failed:");
    }
}

在我的机器上它会输出

 strtoul failed: Numerical result out of range

你犯了两个错误:返回的值strtoul是一个unsignedlong;即使这样,您的值也是 128 位,比unsigned long任何常见平台上的值都大。


而且,不要限制str1- 它应该至少是 33 个字符的长度;或改用指向字符的指针:

char *str1 = "88CC6069E4EDF969773369F988CC969F";

并且,int main(void)

于 2017-05-22T12:18:17.010 回答
0

另一个手动版本:

#include <ctype.h> // To use isdigit(), this function is not necessary if you can use ASCII table

const int asciiNumberBetweenDigitAndAlpha = 7; // see ASCII table
int str2[32];
const int size = sizeof(str1);

for (int i = 0; i < size - 1; i++)
{
    if (isdigit(readLine[i]))
        str2[i] = str1[i] - '0'; // In ASCII '0' = 48; '1' = 49..
    else
        str2[i] = str1[i] - '0' - asciiNumberBetweenDigitAndAlpha;
}

您可以使用,作为丑陋else部分的替代品:

if (str1[i] == 'A')
   str2[i] = 10;
else if (str1[i] == 'B')
   str2[i] = 11;
...
于 2017-05-22T12:28:03.387 回答
-1

用于strtoull更大的数字。

https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.bpxbd00/strtoull.htm

于 2018-09-13T17:31:26.957 回答