开发者

32 bit hex to 32 bit floating point (IEEE 754) conversion in matlab

开发者 https://www.devze.com 2023-02-15 07:26 出处:网络
How can I change the 32 bit hex-value to a floating point value according to the IEEE 754? EDIT: ... data = fread(fid,1,\'float32\');

How can I change the 32 bit hex-value to a floating point value according to the IEEE 754?

EDIT:

...
data = fread(fid,1,'float32');
disp(data);
...

I get this answer开发者_Python百科:

4.2950e+009 1.6274e+009 ...

But how do I get 32 bit floating point (IEEE 754) numbers?


Based on one of your comments it appears that your hexadecimal values are stored as strings of characters in a file. You first want to read these characters from the file in groups of 8. Depending on the specific format of your file (e.g. each set of 8 characters is on its own line, or they're separated by commas, etc.), you could use functions like FSCANF or TEXTSCAN to do this. For example, if your data file looks like this:

409BFFFF
3B3C0000
85E60000

Then you can read the data into a character array like so:

fid = fopen(fileName,'r');  %# Open the file
data = textscan(fid,'%s');  %# Read the data
charArray = char(data{1});  %# Create a character array
fclose(fid);                %# Close the file

Now you need to convert these 32-bit hexadecimal strings to single-precision representations. The easiest way by far is to use the function HEX2DEC to convert the strings to integers (stored as double-precision values), convert them to unsigned 32-bit integers using the function UINT32, then cast the 32-bit integers to single-precision representations using the function TYPECAST. Applying this to the sample data I have above gives these results:

>> values = typecast(uint32(hex2dec(charArray)),'single');
>> fprintf('% 1.42f\n',values);  %# Display the values
 4.874999523162841800000000000000000000000000
 0.002868652343750000000000000000000000000000
-0.000000000000000000000000000000000021629096

You can confirm that these results are correct using this online hexadecimal-to-floating-point converter.


In case anyone is interested, you can do the above type conversion yourself using the function HEX2DEC to first convert the string to an integer representation, then the function BITGET to extract and process the bits for the sign, exponent, and fraction of the single-precision number. For example:

>> a = '409BFFFF';  %# A sample hexadecimal value
>> b = hex2dec(a);  %# Convert to an integer
>> sign = bitget(b,32);                               %# Compute the sign
>> exponent = bitget(b,24:31)*2.^(0:7).';            %'# Compute the exponent
>> fraction = bitget(b,1:23)*2.^(-23:-1).';          %'# Compute the fraction
>> value = (-1)^sign*(1+fraction)*2^(exponent-127);   %# Compute the value
>> fprintf('%1.7f\n',value)                           %# Display the value
4.8749995
0

精彩评论

暂无评论...
验证码 换一张
取 消