hex2num can't recover value from the hex by num2hex

2 ビュー (過去 30 日間)
david wang
david wang 2019 年 12 月 19 日
コメント済み: Walter Roberson 2019 年 12 月 21 日
my matlab script
num2hex(single(-1.7783722e-1))
ans =
'be361af6'
and
hex2num('be361af6')
ans =
-5.146794990196213e-09
why I can not recover the original value ?

採用された回答

Rik
Rik 2019 年 12 月 19 日
As the documentation explains, hex2num assumes the hex is a representation of a double, while num2hex also supports the single data type. That means that despite the names, these two functions are not the exact mirror of each other.
It looks like you will have to implement hex2num yourself if you want to have a single as an output.
  1 件のコメント
david wang
david wang 2019 年 12 月 21 日
Rik: thanks for the answer and explanation !

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

その他の回答 (1 件)

James Tursa
James Tursa 2019 年 12 月 19 日
Try
typecast(uint32(hex2dec('be361af6')),'single')
  2 件のコメント
david wang
david wang 2019 年 12 月 21 日
it works. Thanks.
Walter Roberson
Walter Roberson 2019 年 12 月 21 日
This will work for the case of single, but hex2dec() cannot substitute for hex2num() for the case where the input is representing double: for a lot of the important range, the decimal results produced by hex2num() would be outside what can be represented as double precision.
Instead of hex2dec, the form that is more generally usable is
sscanf(HEXSTRING, '%lx')
which gives back a uint64 that you can then typecast.
typecast(uint32(sscanf('be361af6', '%lx')),'single')
typecast(sscanf('400921fb54442d18', '%lx'), 'double')

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

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

製品


リリース

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by