sscanf with hexadecimal negative value

2019-09-08 01:36发布

I need to convert hexadecimal 4-digits values to decimal so I used ssscanf but it is not work on negative numbers... For example, int test; sscanf("0xfff6","%x",&test); return 65526 instead of -10. How can I resolve that ?

4条回答
Animai°情兽
2楼-- · 2019-09-08 01:44

It's probably because your integers are more than 16 bits wide so that fff6 is indeed positive - you may need fffffff6 or even wider to properly represent a negative number.

To fix this, simply place the following after the scanf:

if (val > 32767) val -= 65536;

This adjust values with the top bit set (in 16-bit terms) to be negative.

查看更多
成全新的幸福
3楼-- · 2019-09-08 01:46

The fact that the value of test is greater than 32k indicates it's a "long" integer (32 bit)...thus it doesn't see the sign bit. You would have to read the value into an unsigned short integer, then type cast it to a signed short, in order to see the negative value...

查看更多
对你真心纯属浪费
4楼-- · 2019-09-08 01:52

You have to do it manually. x conversion specifier performs a conversion from an unsigned int and it requires an argument of type pointer to unsigned int. For example with a cast:

unsigned int test;
int result;

sscanf("0xfff6","%x", &test);
result = (int16_t) test;
查看更多
在下西门庆
5楼-- · 2019-09-08 02:03

I think the core issue is that you are assuming that an int is 16 bits, whereas in your system it appears to be larger than that.

Int is always signed, so the fact that it is reporting the result as 65525 proves that INT_MAX is greater than the 16 bit value of 36727.

Try changing your code from int text to short test and I suspect it will work.

查看更多
登录 后发表回答