convert string into signed int

2019-02-18 06:40发布

问题:

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?

回答1:

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;


回答2:

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)
   ...


回答3:

strtol converts string to long integer

  • http://www.cplusplus.com/reference/clibrary/cstdlib/strtol/

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.

  • http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/


回答4:

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



回答5:

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;


回答6:

Use strtol which converts string to a long integer.