How to truncate a binary number and else?

7 views (last 30 days)
Marcela Matos
Marcela Matos on 16 Mar 2020
Commented: Walter Roberson on 19 Mar 2020
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 Comments
Walter Roberson
Walter Roberson on 16 Mar 2020
N = '10101010100011110101110000';
sum((N-'0').*2.^(3-(1:length(N))))
Walter Roberson
Walter Roberson on 16 Mar 2020
This code does not require that all of N be processed.

Sign in to comment.

Answers (1)

Aghamarsh Varanasi
Aghamarsh Varanasi on 19 Mar 2020
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 Comment
Walter Roberson
Walter Roberson on 19 Mar 2020
% 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.

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!