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

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일

0 개 추천

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

% 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.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Numeric Types에 대해 자세히 알아보기

태그

질문:

2020년 3월 16일

댓글:

2020년 3월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by