sscanf not reading signed hex strings

8 views (last 30 days)
David
David on 5 Mar 2014
Commented: dpb on 6 Mar 2014
It seems that sscanf is always returning saturated unsigned interpretations of hex strings.
text='0xFF884433';
a=sscanf(text,'%i',Inf)
b=sscanf(text,'%x',Inf)
a returns a saturated int32 value (2^31-1) b returns a saturated uint32 value (2^32-1), both are positive, but both are wrong, as the result for signed integer %i with hex interpretation (0x at the beginning) should be -7846861.
Of course the problem can be solved with double(typecast(uint32(sscanf(text, '%x')),'int32')) but I guess this is just a workaround. Is there a possibility to get the right signed numbers from the start?
  1 Comment
dpb
dpb on 5 Mar 2014
I don't know C rules well enough to know but I'm like you, it seems by the description in the Matlab documentation that the '%i' form should return a signed value. The problem I think is in what Matlab decides is the class of the return value whereas in C one can specify it. In the doc for the output of fscanf there's the following --
If the format includes:
Only numeric specifiers, A is numeric. If format includes only 64-bit signed integer specifiers, A is of class int64. Similarly, if format includes only 64-bit unsigned integer specifiers, A is of class uint64. Otherwise, A is of class double.
I think the problem is in the size of in64--the input is positive there and afaict there's no way to force a 32-bit assumption in the interpretation with sscanf.
Unfortunately, one still gets the same result if one extends to 64 bits and uses the '%li' form -- the class is returned as int64, but Matlab still interprets as unsigned.
I've had similar difficulties in the past with signed integers and trying to beat Matlab into submission -- I have occasionally resorted to writing a Fortran mex function.
As stated initially, I don't know if the behavior mimics C or not -- it it doesn't I'd venture to call it a bug; if it does then that'll be the TMW position, too, I'd wager.
So, no answer, just my observations...

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 5 Mar 2014
MATLAB always treats hex input as non-negative.
  8 Comments
dpb
dpb on 6 Mar 2014
Oh, I thunk you were implying something different in evaluation rather than just class...sorry, my bad.

Sign in to comment.

Categories

Find more on Numeric Types in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!