필터 지우기
필터 지우기

Hex to float like python struct.unpack()

조회 수: 34 (최근 30일)
Sebastian Thuné
Sebastian Thuné 2020년 9월 16일
답변: James Tursa 2020년 9월 16일
Hi
I'm trying to convert a hex string to a float in the same manner python function struct.unpack(), https://docs.python.org/3/library/struct.html , which is using the IEEE754 binary32 0r 64 depending on foat or double.
As an example I have
hex = 'C956F53D'
When i run it in a struct.unpack() i get the value:
data = 0.1198
And this is correct. However, when i try the following matlab function i get something totally different.
>> hex2dec(hex)
ans =
3.3779e+09
>> typecast(uint32(hex2dec(hex)),'single')
ans =
single
-8.8047e+05
Does anybody know the difference or what I'm doing wrong?
Thanks!

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 9월 16일
This is the correct way
hex = 'C956F53D';
x = hex2dec(reshape(hex, 2, []).');
dec = typecast(uint8(x), 'single')
  댓글 수: 2
Sebastian Thuné
Sebastian Thuné 2020년 9월 16일
You my friend are a superstar! Thanks!
So i basically have to put the bytes in an array first. Why is that? Is it because typecast has to go byte by byte?
Ameer Hamza
Ameer Hamza 2020년 9월 16일
편집: Ameer Hamza 2020년 9월 16일
Yes, you need to convert it into an uint8 array. Then MATLAB reads the bytes from the input array and converts those bytes into 'single'. It is pretty similar to pointer typecasting in C.
I am glad to be of help!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

James Tursa
James Tursa 2020년 9월 16일
Could be a Big Endian vs Little Endian thing. E.g., inserting a swapbytes( ) step:
>> hex = 'C956F53D'
hex =
'C956F53D'
>> typecast(swapbytes(uint32(hex2dec(hex))),'single')
ans =
single
0.1198

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by