Typecast a hex string to single

6 views (last 30 days)
Michael on 17 Aug 2022
Commented: Michael on 19 Aug 2022
I have strings of hex values that I need to typecast to single precision values. I don't actually care about the actual single precision value, I am just trying to package the binary into a single datatype for transmission.
I want something like
MyHexString = '7f8e2d38';
out = typecast(MyHexString,'single'); %This doesn't work because typecast needs number
But the typecast.m function requires a numeric value. All I want to do is to produce the single precision number equivalent of the binary data held in my hex string.
FYI: I was using
out = typecast(uint32(hex2dec(MyHexString)),'single');
This worked most of the time but is occasionally produced incorrect results because the hex2dec function produces a double and there is some loss on the subsequent uint32 cast. At least that's what I think is wrong.
How to I package hex into a single datatype?
James Tursa
James Tursa on 18 Aug 2022
Edited: James Tursa on 18 Aug 2022
"... occasionally produced incorrect results ..."
Can you post some specific examples where this happens? How can there be a loss converting to uint32?

Sign in to comment.

Accepted Answer

Jan on 18 Aug 2022
Edited: Jan on 18 Aug 2022
str = '7f8e2d38';
vec = uint8(sscanf(str, '%2x'));
num = typecast(vec, 'single')
num = single 4.1379e-05
num = typecast(flip(vec), 'single') % Maybe MSB?
num = single NaN
NaN due to initial 7f
Michael on 19 Aug 2022
Yes. That's what I was originally doing i.e. transmitting the raw binary. I believe the main issues I was having is that I was converting the double to a hex and then splitting up that hex. When one part of the resulting split hex string would result in a NaN value, using () +1i() in matlab would then force the other part of the number to be NaN as well. I got around that by using complext(real, imag). The code I posted above that splits the digits rather than the hex seems to do what I need related to transmitting time values. I believe that the transmission of the raw binary would work as well. Thanks for all your help!

Sign in to comment.

More Answers (0)


Find more on Numeric Types in Help Center and File Exchange




Community Treasure Hunt

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

Start Hunting!