How to truncate a binary number and else?

6 ビュー (過去 30 日間)
Marcela Matos
Marcela Matos 2020 年 3 月 16 日
コメント済み: Walter Roberson 2020 年 3 月 19 日
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 Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by