tags:

views:

156

answers:

6

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?

A: 
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;
Marcelo Cantos
char buf = "fb869e" - I want to convert into signed int. The o/p should be -293218. I just tried converting string into long int. But I'm not getting the negative value.
ulaganathan
char buf = "fb869e". I want to convert this into signed int. So o/p should be -293218. I just tried converting string into long using strtol. But I'm not getting the negative values. My hex values are follows. I need o/p in signed int. "C programming"80000efcc15e7ffffe0b778e80000eee4dae7ffffe1b1e5e80000ede2b9e7ffffe2b8c4e80000ece2e1e7ffffe
ulaganathan
@ulganathan: There was a bug in my answer. Use `if (n > 0x7fffff)...` instead.
Marcelo Cantos
A: 

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.

pyfunc
A: 

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

Peter Miehle
char buf = "fb869e". I want to convert this into signed int. So o/p should be -293218. My hex values are follows. I need o/p in signed int.80000efcc15e7ffffe0b778e80000eee4dae7ffffe1b1e5e80000ede2b9e7ffffe2b8c4e80000ece2e1e7ffffe
ulaganathan
A: 

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;
caf
thanks a lot....This thing screwed up me for last 3 hours...Once again thanks a lot for your help....
ulaganathan
A: 

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)
   ...
Remy Lebeau - TeamB
Thanks for your reply......
ulaganathan