python_user
python_user

Reputation: 186

Converting char hex string to unsigned int using strtoul function in C

I am tring to convert hex to unsigned int from strtoul function. But I am getting output as ffffffff. I have used stdlib.h library. Can someone tell me at what part I am wrong?

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);
}

Upvotes: -4

Views: 2214

Answers (3)

C11 7.22.1.4p8:

The strtol, strtoll, strtoul, and strtoull functions return the converted value, if any. If no conversion could be performed, zero is returned. If the correct value is outside the range of representable values, LONG_MIN, LONG_MAX, LLONG_MIN, LLONG_MAX, ULONG_MAX, or ULLONG_MAX is returned (according to the return type and sign of the value, if any), and the value of the macro ERANGE is stored in errno.

Try the following code:

#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:");
    }
}

On my machine it will output

 strtoul failed: Numerical result out of range

You make 2 mistakes: the value returned by strtoul is an unsignedlong; and even then, your value is 128 bits which is larger than the unsigned long on any common platform.


And also, do not bound the length of str1 - it should be at least 33 characters; or use a pointer-to-char instead:

char *str1 = "88CC6069E4EDF969773369F988CC969F";

And, int main(void).

Upvotes: 1

Badda
Badda

Reputation: 1369

Another manual version :

#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;
}

You could use, as an alternative to the ugly elsepart :

if (str1[i] == 'A')
   str2[i] = 10;
else if (str1[i] == 'B')
   str2[i] = 11;
...

Upvotes: 0

Related Questions