How to use half.typecast

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?

 Accepted Answer

James Tursa
James Tursa on 5 May 2026 at 19:09
Edited: James Tursa about 21 hours ago
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 Comments

Anthony
Anthony about 1 hour ago
Moved: Steven Lord 13 minutes ago
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.
I figured it out, it's using a scalar. Thanks for all the help, this thread is done.

Sign in to comment.

More Answers (0)

Products

Release

R2024a

Asked:

on 5 May 2026 at 18:42

Commented:

about 13 hours ago

Community Treasure Hunt

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

Start Hunting!