Typecast a hex string to single
35 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Michael
el 17 de Ag. de 2022
Comentada: Michael
el 19 de Ag. de 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?
2 comentarios
James Tursa
el 18 de Ag. de 2022
Editada: James Tursa
el 18 de Ag. de 2022
"... occasionally produced incorrect results ..."
Can you post some specific examples where this happens? How can there be a loss converting to uint32?
Respuesta aceptada
Jan
el 18 de Ag. de 2022
Editada: Jan
el 18 de Ag. de 2022
str = '7f8e2d38';
vec = uint8(sscanf(str, '%2x'));
num = typecast(vec, 'single')
num = typecast(flip(vec), 'single') % Maybe MSB?
NaN due to initial 7f
13 comentarios
Walter Roberson
el 19 de Ag. de 2022
You are transmitting in binary, right? Rather than formatting the single precision data as text?
Because if so then it does not matter that the printable version of a series of bytes might be NaN, as long as the byte sequence is exactly recoverable when transmitted in binary.
format long g
s = '7f8e2d38';
d = uint8(sscanf(s, '%2x').')
df = typecast(fliplr(d), 'single')
typecast(df, 'uint8')
filename = tempname();
fid = fopen(filename, 'w')
fwrite(fid, df, 'single')
fclose(fid)
ls('-l', filename)
fid = fopen(filename, 'r')
dfr = fread(fid, '*single')
fclose(fid)
typecast(dfr, 'uint8')
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!