32-bit floating point conversion (IEEE 754) with hexadecimal or 32-bit matrix conversion

How to change a 32-bit hexadecimal value to a floating point value according to IEEE 754?

EDIT:

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

I get the answer:

4.2950e + 009 1.6274e + 009 ...

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

+2
source share
1 answer

Based on one of your comments, it seems your hexadecimal values ​​are stored as character strings in a file. First you want to read these characters from the file in groups of 8. Depending on the specific format of your file (for example, each set of 8 characters is on a separate line or they are separated by commas, etc.), you can use functions such as FSCANF or TEXTSCAN to do this. For example, if your data file looks like this:

 409BFFFF 3B3C0000 85E60000 

Then you can read the data in an array of characters as follows:

 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 hex strings to representations with one precision. The easiest way is to use the HEX2DEC function to convert strings to integers (stored as double precision values), convert them to unsigned 32-bit integers using the UINT32 function, then convert 32-bit integers to single-precision representations using TYPECAST function. Applying this to the sample data given above, the following results are given:

 >> 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 converter with a hexadecimal convertible point in HTML format .


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

 >> 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 
+3
source

Source: https://habr.com/ru/post/1369187/


All Articles