Challanges representing hexadecimal values as "integer double" in uitable
이전 댓글 표시
In a uitable, I’m editing multiple cells and I want to use hexadecimal (integer) as the input value. For most cases this turns out perfectly fine. However, hexadecimal values ending with 'e' are causing me a headache. It seems that Matlab interprets the input as string and converts the hexadecimal input (0xXXXX, without quotation marks) using ‘str2double’ before any callbacks are triggered. ‘str2double’ uses ‘sscanf’ behind the scenes and in ‘str2double’, ‘sscanf’ is called with format specifier ‘%f’. This makes sense when ‘str2double’ tries to convert to a double value. When ‘sscanf’ is called with ‘%f’, it probably triggers on the trailing ‘e’ for scientific notation. There is no value proceeding ‘e’ and ‘str2double’ fails to read the entire char-array and returns NaN.
I am able to catch the NaN-value and re-evaluate the string using ‘myStr2double’, where I call ‘sscanf’ with format specifier ‘%i’. This works, but it seems like an unnecessary step as not doing this works for all hexadecimal values (I’ve tested) except for those ending with ‘e’.
Here are some sample code to illustrate the problem:
str2double('0x1234')
returns 4660 (as expected)
str2double('0x123e')
returns NaN.
Is there a better solution to this behaviour, or am I trying to do something that is just outside of the intention?
In ‘myStr2double’, i call:
[a,count,errmsg,nextindex] = sscanf(s,'%i',1)
to read the entire hexadecimal char-array.
댓글 수: 3
Tord Fjordheim Onstein
2021년 9월 10일
"...am I trying to do something that is just outside of the intention?"
Yes. STR2DOUBLE is not documenented to convert hexadecimal numbers. For reliable conversion use functions which are designed and documented for converting hexadecimal, e.g. HEX2DEC, SSCANF.
Tord Fjordheim Onstein
2021년 12월 20일
답변 (1개)
Maybe using hex2dec instead of str2double will work:
str2double('0x1234')
str2double('0x123e')
hex2dec('0x1234')
hex2dec('0x123e')
댓글 수: 4
Another option is to use SSCANF:
sscanf('0x1234','%x')
sscanf('0x123e','%x')
Tord Fjordheim Onstein
2021년 12월 20일
Walter Roberson
2021년 12월 20일
preprocess to determine which conversion to apply.
Tord Fjordheim Onstein
2021년 12월 20일
카테고리
도움말 센터 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!