1
votes

I want to know if it's possible in MATLAB to discard overflow digits in MATLAB when I add two binary numbers.

I've only been able to find how to have a least number of binary digits, but how to I set a maximum number of digits?

For example:

e = dec2bin(bin2dec('1001') + bin2dec('1000'))

That gave me:

e =

10001

How do I get only '0001'?

2

2 Answers

4
votes

dec2bin will always give you the minimum amount of bits to represent a number. If you would like to retain the n least significant digits, you have to index into the string and grab those yourself.

Specifically, if you want to retain only the n least significant digits, given that you have a base-10 number stored in num, you would do this:

out = dec2bin(num);
out = out(end-n+1:end);

Bear in mind that this performs no error checking. Should n be larger than the total number of bits in the string, you will get an out of bounds error. I'm assuming you're smart enough to use this and know what you're doing.

So for your example:

e = dec2bin(bin2dec('1001') + bin2dec('1000'));

n = 4, and so:

>> n = 4;
>> e = e(end-n+1:end)

e =

0001
1
votes

Here is a more robust (but less efficient, I fear) way: What you describe is exactly the modulo operation. A 4-bit binary number is the remainder after a division by 0b10000 = 16. This can be done using the mod function in MATLAB.

>> e = dec2bin(mod(bin2dec('1001') + bin2dec('1000'),16),4)

e =

0001

Note: I added 4 as additional argument to the dec2bin function, so the output will always be 4-bit wide.

This can of course be generalized to any bit width: If you want to add 8-bit numbers, you will need the remainder of the division by 0b1'0000'0000 = 256, for example

>> e = dec2bin(mod(bin2dec('10011001') + bin2dec('10001000'),256),8)

e =

00100001

Or for shorter numbers, e.g. 2-bit wide, it is 0b100 = 4:

>> e = dec2bin(mod(bin2dec('10') + bin2dec('11'),4),2)

e =

01