Nikos
Nikos

Reputation: 724

Negative integer to signed 32-bit binary

>>> a = -2147458560
>>> bin(a)
'-0b1111111111111111001111000000000'

My intention is to manipulate a as 32-bit signed binary and return it. The correct conversion for -2147458560 would be '0b10000000000000000110001000000000'; how can I achieve that?

Upvotes: 9

Views: 11710

Answers (1)

falsetru
falsetru

Reputation: 369424

Bitwise AND (&) with 0xffffffff (232 - 1) first:

>>> a = -2147458560
>>> bin(a & 0xffffffff)
'0b10000000000000000110001000000000'

>>> format(a & 0xffffffff, '32b')
'10000000000000000110001000000000'
>>> '{:32b}'.format(a & 0xffffffff)
'10000000000000000110001000000000'

Upvotes: 22

Related Questions