ulaganathan
ulaganathan

Reputation: 79

convert string into signed int

I want to convert a string into a signed int. Following is the requirement. I have stored hex value as a string in buffer. Now I want to convert that value into signed int.

buf = "fb869e" Convert this into signed int. So o/p should be -293218. but when I'm trying to convert using strtol I'm getting 16483998. So what I should I do?

Upvotes: 4

Views: 14252

Answers (7)

Dig The Code
Dig The Code

Reputation: 692

Try below block of code, its working for me.

char *p = "0x820";
uint16_t intVal;
sscanf(p, "%x", &intVal);

printf("value x: %x - %d", intVal, intVal);

Output is:

value x: 820 - 2080

Upvotes: 0

Alex Lockwood
Alex Lockwood

Reputation: 83313

Use strtol which converts string to a long integer.

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 596592

Others have suggested strtol(). I just want to mention sscanf() as an alternative, eg:

int i;
char *buf = "fb869e";
if (sscanf(buf, "%x", &i) == 1)
   ...

Upvotes: 1

Marcelo Cantos
Marcelo Cantos

Reputation: 185892

0xfb869e == 0x00fb869e == 16483998

As a signed integer, the high bit must be set to produce a negative number. Since the high bit of the given number isn't set, it must be positive.

If you want the number to be treated as a 24-bit number, you'll have to pad bit 23 out to the remaining high-bits. Here's one way to do it:

long n = strtol(...);
if (n > 0xffffff) n |= 0xff000000;

Upvotes: 0

caf
caf

Reputation: 239071

The hexadecimal number 0xfb869e is not negative. The inbuilt number conversion functions will not convert it to a negative value, since its value is positive.

What you are saying is that this is the unsigned hexadecimal equivalent of a 24-bit 2s complement negative number, and you want that number. The way to get that is to convert it to the positive number, then use calculations to convert it to the 24-bit 2s complement equivalent:

char *buf = "fb869e";
long n;

n = strtol(buf, NULL, 16);
if (n > 0x7fffffL)
    n -= 0x1000000L;

Upvotes: 5

Peter Miehle
Peter Miehle

Reputation: 6070

why should 0x00fb869e be a negative number? you should have to provide the base of your number system, to even be allowed to tell, whether a value in one format is a negative in another format

Upvotes: 0

pyfunc
pyfunc

Reputation: 66719

strtol converts string to long integer

The output is correct and it will be 16483998

And if you use atoi, while it converts to string to integer, the correct value if out of the range of representable values, INT_MAX or INT_MIN is returned.

Upvotes: 0

Related Questions