How to truncate a binary number and else?

21 次查看(过去 30 天)
Having a binary number:
101.010101000111101011100001
  1. 101.01010100011110101110000
  2. 101.01010100011110101110001
  1. Truncate de binary number (IEEE 754) That my binary number only have 23 digits on the right
  2. That the binary number have only 23 digits on the right but not with truncation but to round. If the 24th digit is 1 then it must add it to the 23th digit etc)
How do I do that in matlab?
  2 个评论
Walter Roberson
Walter Roberson 2020-3-16
N = '10101010100011110101110000';
sum((N-'0').*2.^(3-(1:length(N))))
Walter Roberson
Walter Roberson 2020-3-16
This code does not require that all of N be processed.

请先登录,再进行评论。

回答(1 个)

Aghamarsh Varanasi
Aghamarsh Varanasi 2020-3-19
Hi,
I understand that you want to implement truncate and round-off operations on binary numbers. Considering that the binary numbers are stored as strings in MATLAB, we can implement the truncate and round-off operations as,
Truncate
N = '101.010101000111101011100001';
%index at which the binary number ends -- 23 digits to right of decimal
index = strfind(N,'.')+23;
% truncate
N = N(1:min(index,length(N)));
Round off
N = '101.010101000111101011100001';
%index at which the binary number ends -- 23 digits to right of decimal
index = strfind(N,'.')+23;
if index < length(N)
roundOffPart = N(index:end);
%truncate N
N = N(1:min(index,length(N)));
% If there is 1 in the string after 23 digits
% carry it farward to N
if contains(roundOffPart,'1')
N(end) = '1';
end
end
Hope this helps
  1 个评论
Walter Roberson
Walter Roberson 2020-3-19
% If there is 1 in the string after 23 digits
% carry it farward to N
That would be rounding up, but the user only asked for rounding, so only the location immediately after 23 needs to be checked. Unless the user did not explain properly, as rounding-up is a valid thing to want to do and maybe was intended.
if contains(roundOffPart,'1')
N(end) = '1';
end
But suppose that N(end) is already '1'. Which is the case. The number has been carefully constructed so that rounding up would require carrying the '1' by several places. Possibly past the decimal point.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by