äymm
äymm

Reputation: 411

Get uint from hex-string in C

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

Answers (4)

MOHAMED
MOHAMED

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

autistic
autistic

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

Mahmoud Samy
Mahmoud Samy

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

BLUEPIXY
BLUEPIXY

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

Related Questions