Problem with decimal to binary conversion

3 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2017-2-8
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.

请先登录,再进行评论。

回答(2 个)

Image Analyst
Image Analyst 2017-2-7
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 2017-2-7
Fiona,
The output makes sense:
87 = 0*128 + 1*64 + 0*32 + 1*16 + 0*8 + 1*4 + 1*2 + 1*1

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by