Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get binary representation of negative numbers in python [duplicate]

Tags:

python

bit

When I enter bin(-3) it just shows -0b11.

Which is not what I want. It just keeps that - sign and convert the number. I want the actual representation of negative numbers.

Is there any method in python which does that?

like image 936
Bhavesh Munot Avatar asked Feb 07 '15 14:02

Bhavesh Munot


People also ask

How are negative numbers represented in binary Python?

Negative numbers are written with a leading one instead of a leading zero. So if you are using only 8 bits for your twos-complement numbers, then you treat patterns from "00000000" to "01111111" as the whole numbers from 0 to 127, and reserve "1xxxxxxx" for writing negative numbers.

How do you show negatives in binary?

The simplest is to simply use the leftmost digit of the number as a special value to represent the sign of the number: 0 = positive, 1 = negative. For example, a value of positive 12 (decimal) would be written as 01100 in binary, but negative 12 (decimal) would be written as 11100.

Can you represent negative numbers in binary?

Two's Complement of a Signed Binary Number In two's complement, the positive numbers are exactly the same as before for unsigned binary numbers. A negative number, however, is represented by a binary number, which when added to its corresponding positive equivalent results in zero.

How do you represent negative 2 in binary?

If the number is negative then it is represented using 1's complement. First represent the number with positive sign and then take 1's complement of that number. (ii) Take 1's complement of 0 0101 and that is 1 1010. MSB is 1 which indicates that number is negative.


1 Answers

Depending on how many binary digit you want, subtract from a number (2n):

>>> bin((1 << 8) - 1)
'0b11111111'
>>> bin((1 << 16) - 1)
'0b1111111111111111'
>>> bin((1 << 32) - 1)
'0b11111111111111111111111111111111'

UPDATE

Using following expression, you can cover both positive and negative case:

>>> bin(((1 << 32) - 1) & -5)
'0b11111111111111111111111111111011'
like image 185
falsetru Avatar answered Oct 25 '22 02:10

falsetru