Reputation: 10742
I was asked in a class:
What is the least number of bits are required to represent the following decimal numbers as 2’s complement binary numbers? -64 31 128
So, first of all, what is the difference between 1 and 2's complement binary? How can I convert a decimal number into a 2's complement binary representation?
I also am wondering, is it possible to have multiple representations of that decimal number? How do I find out the least number of required bits?
Upvotes: 1
Views: 8047
Reputation: 111239
The difference between 1's and 2's complement:
Multiple representations of a decimal number in binary: The representation of a number in binary is unique, but for one exception: in 1's complement the number 0 can be written both as 0 and as ..111.
Note that in both cases negative numbers have a representation with an infinite string of 1's on the left. In practice the number of bits available is finite, so we use only some of the rightmost bits. The convention is that if the leftmost bit is 1 we assume that the number has an infinite string on ones to the left before this first bit. This means that the leftmost bit gives the sign of the number: if it's 1 the number is negative, if it's 0 the number is positive. The rest of the bits give the magnitude. (Of course, there are other ways to represent signed numbers where this doesn't hold.)
The least number of bits required to represent a number may differ between 1's and 2's complement. For example, 1's complement needs at least 5 bits to represent -8, while 2's complement can make do with 4:
+8 in binary: 1000
-8 in 1's complement: 10111
-8 in 2's complement: 1000
Upvotes: 4