如何根据 IEEE 754 将 32 位十六进制值更改为浮点值?
编辑:
...
data = fread(fid,1,'float32');
disp(data);
...
我得到这个答案:
4.2950e+009 1.6274e+009 ...
但是如何获得 32 位浮点 (IEEE 754) 数字?
最佳答案
根据您的评论之一,您的十六进制值似乎以字符串形式存储在文件中。您首先要从文件中以 8 个字符为一组读取这些字符。根据文件的具体格式(例如,每组 8 个字符各占一行,或者它们之间用逗号分隔等),您可以使用类似 FSCANF 的函数或TEXTSCAN去做这个。例如,如果您的数据文件如下所示:
409BFFFF
3B3C0000
85E60000
然后您可以将数据读入字符数组,如下所示:
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
现在您需要将这些 32 位十六进制字符串转换为单精度表示形式。迄今为止最简单的方法是使用函数 HEX2DEC要将字符串转换为整数(存储为 double 值),请使用函数 UINT32 将它们转换为无符号 32 位整数。 ,然后使用函数 TYPECAST 将 32 位整数转换为单精度表示形式。将其应用于上面的示例数据会得到以下结果:
>> values = typecast(uint32(hex2dec(charArray)),'single');
>> fprintf('% 1.42f\n',values); %# Display the values
4.874999523162841800000000000000000000000000
0.002868652343750000000000000000000000000000
-0.000000000000000000000000000000000021629096
您可以使用 this online hexadecimal-to-floating-point converter 确认这些结果是否正确。 .
如果有人感兴趣,您可以使用函数 HEX2DEC 自己进行上述类型转换。首先将字符串转换为整数表示,然后使用函数 BITGET提取并处理 sign, exponent, and fraction of the single-precision number 的位。例如:
>> 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
关于matlab - matlab中32位十六进制到32位浮点(IEEE 754)的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5232726/