sscanf not reading signed hex strings

5 ビュー (過去 30 日間)
David
David 2014 年 3 月 5 日
コメント済み: dpb 2014 年 3 月 6 日
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 件のコメント
dpb
dpb 2014 年 3 月 5 日
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...

サインインしてコメントする。

回答 (1 件)

Walter Roberson
Walter Roberson 2014 年 3 月 5 日
MATLAB always treats hex input as non-negative.
  8 件のコメント
Walter Roberson
Walter Roberson 2014 年 3 月 6 日
I think I said that ;-)
dpb
dpb 2014 年 3 月 6 日
Oh, I thunk you were implying something different in evaluation rather than just class...sorry, my bad.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeNumeric Types についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by