Effacer les filtres
Effacer les filtres

Problem with decimal to binary conversion

3 vues (au cours des 30 derniers jours)
fiona rozario
fiona rozario le 7 Fév 2017
Commenté : Stephen23 le 8 Fév 2017
I am using dec2bin() to convert '87' to its binary value. The function is returning '01010111'. I can't understand this output since '0101' is 5 in decimal and '0111' is 7. The output I was expecting was '10000111'.
On the other hand, if I convert just '8' to binary then the output is '1000'. Can someone please explain where I am wrong in my understanding?
  1 commentaire
Stephen23
Stephen23 le 8 Fév 2017
Think about decimal numbers: does 53 have the same value as simply adding the values 5 and 3 ? Think about what the digit positions represent: does the 5 represent the value 5, or does its position tell us that it actually represents 50 ?
In the same way, the positions of the digits in 1000 and 0111 tells us what they represent. Just like with decimals, where the positions represent ...10000,1000,100,10,1... (powers of ten), for binary the positions represent ...256,128,64,32,16,8,4,2,1,... (powers of two).
So when you put 1000b in front of 0111b you did not take into account that the digit positions themselves encode information (the powers of two).
So concatenating 1000b (==8) and 0111b (==7) will not give the same as 10000111b (==135) , for exactly the same reason why 5 in 53 represents a different value to the 5 in 50000: because the digit positions tell us information that we need to take into account in understanding the digit value.

Connectez-vous pour commenter.

Réponses (2)

Image Analyst
Image Analyst le 7 Fév 2017
Why were you expecting that? Why should it give the binary representation for 135 = 2^7 + 2^2 + 2^1 + 2^0 instead of the binary representation for 87 like you asked for?
  1 commentaire
fiona rozario
fiona rozario le 7 Fév 2017
I go my mistake, thanks...

Connectez-vous pour commenter.


Chad Greene
Chad Greene le 7 Fév 2017
Fiona,
The output makes sense:
87 = 0*128 + 1*64 + 0*32 + 1*16 + 0*8 + 1*4 + 1*2 + 1*1
  1 commentaire
fiona rozario
fiona rozario le 7 Fév 2017
I got where I as wrong...thank you

Connectez-vous pour commenter.

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by