Binary addition in MATLAB
Afficher commentaires plus anciens
Is it possible to do binary addition in MATLAB? I tried using the usual add function but it didnt work. I defined 2 numbers as binary digits, say 1010 and 1100. The output came out as 2100. It's a direct addition of 2 numbers.
3 commentaires
Andreas Goser
le 21 Fév 2011
You could help the community to help by giving your code and not speculate
Jan
le 21 Fév 2011
I assume that 1010 and 1100 results in 2110 and not 2100.
"Is it possible to do binary addition in MATLAB? I tried using the usual add function but it didnt work"
All numbers are binary. When MATLAB adds numbers it is doing very efficient binary addition for you.
N = 0b1010 + 0b1100
dec2bin(N)
Réponse acceptée
Plus de réponses (6)
sundeep cheruku
le 14 Avr 2013
Modifié(e) : Walter Roberson
le 14 Avr 2013
fliplr(de2bi(bi2de(fliplr([1 0 1 0]))+bi2de(fliplr([1 1 0 0]))))
while using bi2de or de2bi it takes the first bit as LSB and last bit as MSB so fliplr is necessary to use.
Hope this might work.
1 commentaire
K E
le 22 Juil 2016
For other newbies trying to understand: LSB and MSB are least and most significant bit and the fliplr is to get the bits in the desired order.
Andreas Goser
le 21 Fév 2011
Try:
dec2bin(bin2dec('1010')+bin2dec('1100'))
1 commentaire
Paulo Silva
le 21 Fév 2011
I wonder why matlab doesn't provide a simple way to work with binary numbers just like we do with decimal, these days any cheap calculator can do that.
Paulo Silva
le 21 Fév 2011
0 votes
http://www.mathworks.com/matlabcentral/newsreader/view_thread/257224
1 commentaire
Andreas Goser
le 21 Fév 2011
You were faster... I was also considering to use lmgtfy.com :-)
Datla Ashwin
le 1 Mar 2011
0 votes
1 commentaire
Walter Roberson
le 1 Mar 2011
You haven't defined which variety of binary addition you want.
Nicolás Dueñas
le 2 Août 2016
Modifié(e) : Walter Roberson
le 2 Août 2016
0 votes
Kevin
le 27 Nov 2024
If you don't care about the carry bit:
mod([1 0 1 0] + [1 1 0 0],2)
1 commentaire
That won't work if there's any carrying. Adding 7 and 1 ought to give 8 not 6:
mod([0 1 1 1] + [0 0 0 1], 2)
0b0111 + 0b0001
Catégories
En savoir plus sur Code Generation dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!