Reputation: 186
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
Reputation: 7
use strtoull
for larger numbers.
https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.bpxbd00/strtoull.htm
Upvotes: -1
Reputation: 133948
C11 7.22.1.4p8:
The
strtol
,strtoll
,strtoul
, andstrtoull
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
, orULLONG_MAX
is returned (according to the return type and sign of the value, if any), and the value of the macroERANGE
is stored inerrno
.
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 unsigned
long
; 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
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 else
part :
if (str1[i] == 'A')
str2[i] = 10;
else if (str1[i] == 'B')
str2[i] = 11;
...
Upvotes: 0