Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 893
Nikos Avatar asked Feb 20 '15 14:02

Nikos


1 Answers

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

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

>>> format(a & 0xffffffff, '32b')
'10000000000000000110001000000000'
>>> '{:32b}'.format(a & 0xffffffff)
'10000000000000000110001000000000'
like image 167
falsetru Avatar answered Sep 27 '22 19:09

falsetru