As discussed in class, computer architectures rely on binary numbers (base 2) to
ID: 3818676 • Letter: A
Question
As discussed in class, computer architectures rely on binary numbers (base 2) to do simple arithmetic operations. Since we ar more familiar with the decimal system (base 10), virtually all programming languages offer support for interconverting betwee binary and decimal representations of the same number. In MATLAB, these functions are bi2de and de2bi. A binary vector B is a logical vector (containing 0s or ls only) that encodes a decimal number D using the binary scheme outlined in Figure 1, with the last element being the most significant bit n-1 x 20 x 21 x 2 x 2n U Sum D 32 obi 21b2 22b3 2'n 1bn Figure 1. Write a MATLAB function, C- binaryop(B1, B2, op), that performs a simple arithmetic operation on binary vectors B1 and B2. The text string op can be either as "add' or 'multiply. In the case that op is'add, output the binary vector Cas the sum of the numbers encoded in the binary vectors Bl and B2. If op is 'multiply, then perform a multiplication operation on the numbers encoded in the binary vectors B1 and B2, and output this value in binary as the vector C.Explanation / Answer
function x = bi2de(s)
n = length(s);
twos = pow2(0:1:n-1);
x = twos * s';
end
function s = de2bi(x)
[K,e] = log2(max(x));
s = rem(floor(x*pow2(1-e:0)),2);
end
function C = binaryop(B1, B2, op)
a = bi2de(fliplr( B1 )); %we need to flip the B1 before converting to decimal*
b = bi2de(fliplr( B2 )); %we need to flip the B2 before converting to decimal
if strcmp(op,'multiply')==1 %if the operator is 'multiply'**
x = a*b;
elseif strcmp(op,'add')==1 %if the operator is 'add'
x = a + b;
else %if the operator is none of the above
return ;
end
C = de2bi(x); %finally convert to binary and return
end
NOTE:
* Output of bi2de([1 0 1 1]) is 13 but not 11 so we need to reverse the array before passing the array to the function
** In matlab strcmp() returns 1 if the strings are equal unlike c or c++ where strcmp returns 0 when two strings are equal
I hope you like the code. I have also commented the code to make things easy. Incase you are having doubts with the code, please let me know. I shall be glad to help you with the code.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.