Problem with decimal to binary conversion

2 views (last 30 days)
fiona rozario
fiona rozario on 7 Feb 2017
Commented: Stephen23 on 8 Feb 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 Comment
Stephen23 on 8 Feb 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.

Sign in to comment.

Answers (2)

Image Analyst
Image Analyst on 7 Feb 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?

Chad Greene
Chad Greene on 7 Feb 2017
The output makes sense:
87 = 0*128 + 1*64 + 0*32 + 1*16 + 0*8 + 1*4 + 1*2 + 1*1


Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!