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 CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by