Reputation: 411
Let's say I have a char*
called code, and it has "0x41"
in it.
char *code = "0x41";
How can I convert that into an unsigned int
? (To be exact, I need a WORD
, but that's just an unsigned int
).
Upvotes: 3
Views: 6444
Reputation: 43518
unsigned int h;
sscanf(code, "%x", &h);
EDIT taking account of the remark of ExP : %x
could catch the value in the string "0x41"
Upvotes: 6
Reputation: 15632
I gather you mean that variable declared as char *code = "0x41";
points to the string denoted by "0x41"
.
There is no such thing as a WORD
in C, but if you've got it typedef'd as an unsigned int
, then you can convert this string of hexadecimal digits to an unsigned int
like so:
char *code = "0x41";
unsigned int foo;
assert(sscanf(code, "%X", &foo) == 1);
You may note the use of assert
in this code. I suggest replacing that assertion with logic to report an error when the return value isn't 1, as this would indicate that the string isn't in the correct format to be parsed as specified.
Upvotes: 4
Reputation: 2852
you can use strtol function it convert string to unsigned long integer for any base you want
http://www.cplusplus.com/reference/cstdlib/strtoul/
Upvotes: 2
Reputation: 40145
#include <stdio.h>
#include <stdlib.h>
int main() {
char *code = "0x41";
char *ck;
long unsigned lu;
lu=strtoul(code, &ck, 16);
printf("%lu\n", lu);
return 0;
}
Upvotes: 3