sscanf with hexadecimal negative value

2019-09-08 01:39发布

问题:

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 ?

回答1:

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;


回答2:

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



回答3:

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.



回答4:

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.