这里是一个试图将实数转换为其近似单精度浮点表示的代码,用于教育目的,以演示中间结果:
function [IEEE] = myDec2IEEE (d)
% Accepts a decimal number, d.
% Returns 1x32 bit array holding its closest IEEE representation.
s = getSign(d);
[e, f] = getCharacteristic(d);
binaryE = binStr2binArr(dec2bin(e)); % convert to binary integer array.
if numel(binaryE) < 8 % extend to exponent bits number.
binaryE = [zeros(1, 8 - numel(binaryE)), binaryE];
end
binaryF = expandFractionToBinary(f);
IEEE = [s , binaryE, binaryF];
end
function [B] = binStr2binArr (s)
% Accepts a binary character string, s.
% Returns binary integer array, B.
len = numel(s);
B = zeros(1, len);
for i = 1 : len
B(i) = s(i) - '0';
end
end
function [B] = expandFractionToBinary(f)
% Accepts what has remained from the decimal number
% after the calculation of the exponent, i.e its fractional part.
% Returns a 1x23 binary array which is the approximation of the
% fractional part represented as a sum of negative powers of 2,
% (up to the 22 - nd power).
singlePrecision = 22;
B = zeros(1, singlePrecision); % binary string to store fraction of IEEE754.
i = 1; % exponent of 2; (i+1) -index in binary array.
while f != 0 && i <= singlePrecision
ith = 1 / (2^(i));
if ith <= f
f = f - ith;
B(i) = 1; % include coefficient in the sum.
end
i = i + 1;
end
end
function [e, f] = getCharacteristic (d)
% Accepts a number is base10, d.
% Returns the exponent and fraction in d's IEEE754 representation, in base10.
% write d in base-2 scientific notation
% i.e. factor it into number in the range [1, 2] and a power of 2.
bias = 127;
i = 1;
f = 0;
while ~(f >= 1 && f <= 2)
f = d / (2^(-i));
% pause; % if number > 1 the denominator -> 0 and (faster than f -> Inf)
i = i + 1;
end
i = i - 1; % last check is done after incrementation.
e = bias - i;
f = f - 1;
end
function [s] = getSign (d)
% Accepts a number in base10, d.
% Returns the sign bit of its IEEE754 representation.
if d >= 0
s = 0;
else
s = 1;
end
end
输入:
IEEE = myDec2IEEE(0.085)
输出:
Columns 1 through 21:
0 0 1 1 1 1 0 1 1 0 1 0 1 1 1 0 0 0 0 1 0
Columns 22 through 31:
1 0 0 0 1 1 1 1 0 1
但是,它只适用于0问题
我做错什么了?
如何修改代码以正确返回ieee表示的数字>=1和d注:
基于关系d=(-1)符号*2exponent-bias*(分数+1)的实现,其中分数=和(1/2^n),n=0,…,22;偏差=127。
最佳答案
经证实,MATLAB使用IEEE754进行单精度浮点运算。
因此,为什么不让MATLAB处理内部事务,然后做这样的事情呢?:
s = dec2bin(typecast(single(0.085),'uint32'), 32)
它给出:
00111101101011100001010001111011
这与所需的输出(从您提到的here中)相匹配,也适用于值>1的情况。
如果您需要一个数字,而不是字符串,结果您可以这样转换:
x = s-'0'