开发者

convert string into signed int

开发者 https://www.devze.com 2023-01-18 01:27 出处:网络
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.

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 开发者_如何学Gothis 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?


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;


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


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/


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


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;


Use strtol which converts string to a long integer.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消