# [?] Get the binary of negative integer numbers?

Posted 3 years ago
6402 Views
|
|
2 Total Likes
|
 I have a question about the binary of negative integer number in Mathematica.In most implementations, negative signed integers are stored in what is called two's complement. The other major way of storing negative signed numbers is called one's complement.The two's complement of an N-bit number x is defined as 2^N - x. For example, the two's complement of 8-bit 1 is 2^8 - 1, or 1111 1111. The two's complement of 8-bit 8 is 2^8 - 8, which in binary is 1111 1000. This can also be calculated by flipping the bits of x and adding one. For example:  1 = 0000 0001 ~1 = 1111 1110 -1 = ~1 + 1 = 1111 1111 21 = 0001 0101 ~21 = 1110 1010 -21 = 1110 1011 128 = 1000 0000 ~128 = 0111 1111 -128 = 1000 0000 They can also be calculated as: -1 = 2^8 - 1 = 255 = 1111 1111 -21 = 2^8 - 21 = 234 = 1110 1010 -128 = 2^8 - 128 = 128 = 1000 0000 These results are exactly identical to the results calculated in C language. However, when using Mathematica (I use Mathematica 11.1.0), the results are quite different: BaseForm[-1, 2] = -1 BaseForm[-21, 2] = -10101 BaseForm[-128, 2] = -1000 0000 My question is: How to get the right results using Mathematica? Am I using the WRONG command?Thanks a lot! Answer
 I think you probably want to define your own function, because the builtin functions (that I am aware of) behave differently.For example, it could be (to get n bits) Two[n_,x_]:=IntegerDigits[2^n-x,2,n] Note that BaseForm is good for displaying a number in another base, while IntegerDigits is more useful when you want to keep using the result in further expressions. You might find that one of the Bitwise operation functions is what you want. Answer