I have to read in a 16-bit float from a binary file. I used
x = fread(fid,1,'*uint16','ieee-be') since there is no half data type for fread.
I then tried half.typecast(x) to get the number. The number being put in is uint16 65444. It should return -0.640625. I'm getting NaN back. What could I be doing wrong?

 Réponse acceptée

James Tursa
James Tursa le 5 Mai 2026
Modifié(e) : James Tursa le 5 Mai 2026
k = uint16(65444)
k = uint16 65444
dec2bin(k)
ans = '1111111110100100'
half.typecast(k)
ans = half NaN
The half precision data type has 1 sign bit, 5 exponent bits, and 10 explicit significand bits. So your bit pattern is:
1 11111 1110100100
When all exponent bits are set and the significand is non-zero, that is a NaN. Note that the payload gets preserved in this conversion as demonstrated by the fact that we can recover the original integer bit pattern:
storedInteger(ans)
ans = uint16 65444
Whereas when you create a half NaN from scratch MATLAB uses a predifined payload with only the leading bit set:
dec2bin(storedInteger(half(NaN)))
ans = '1111111000000000'
Note that when you swap bytes on your original value, you still don't get what you expect:
half.typecast(swapbytes(k))
ans = half -0.0195
Are you sure you are working with half data types and not bfloat16 data types?

2 commentaires

Anthony
Anthony le 6 Mai 2026
Déplacé(e) : Steven Lord le 6 Mai 2026
What I'[m doing is reading data from a flight recorder (not the comercial airline type). I found some code my predecessor wrote that looks like this:
Roll = fread(fid,1,'int16=>double','ieee-be'. This angle is in radians. He then multiplies it by 0.00549316 to get the angle in degrees. Any idea how he came up with that formula? It works, I just don't know how.
Anthony
Anthony le 6 Mai 2026
I figured it out, it's using a scalar. Thanks for all the help, this thread is done.

Connectez-vous pour commenter.

Plus de réponses (0)

Produits

Version

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by