convert an negative integer to 32bit binary in python
Question:
I would like to create a function which gives the following things
32_bit_binary(-1) should be '11111111111111111111111111111111'
32_bit_binary(1) should be '00000000000000000000000000000001'
Now I gave the following code
def 32_bit_binary(num_bits):
return '{:032b}'.format(num_bits)
But when I gave this
print(32_bit_binary(-1))
it came -00000000000000000000000000000001
What is wrong with the code?
Answers:
String formatting like {:032b}
does not give you the actual representation of the number. It just writes the number in base-2. That’s a purely mathematical operation. Implementation details like how the computer represents said number (like using binary, using 2’s complement for negative numbers, etc.) are not in the scope of those string formatting operations.
A good way to get at the actual representations of values in Python is the struct
module. For example, struct.pack("@i", -1)
returns the bytestring b'xffxffxffxff'
. Printing that bytestring in binary is left as an exercise to the reader.
PS: For numbers other than -1
, you may be surprised by the output of struct.pack
. The term you’ll want to look up is endianness, and the @
in my struct.pack
formatting string.
As @gspr said, formatting as base 2 doesn’t give you the actual representation. You can solve it by masking the negative integer, which has infinitely many leading 1s for the purposes of bitwise operations, down to 32 bits:
return f"{num_bits & 0xffff_ffff:032b}"
I would like to create a function which gives the following things
32_bit_binary(-1) should be '11111111111111111111111111111111'
32_bit_binary(1) should be '00000000000000000000000000000001'
Now I gave the following code
def 32_bit_binary(num_bits):
return '{:032b}'.format(num_bits)
But when I gave this
print(32_bit_binary(-1))
it came -00000000000000000000000000000001
What is wrong with the code?
String formatting like {:032b}
does not give you the actual representation of the number. It just writes the number in base-2. That’s a purely mathematical operation. Implementation details like how the computer represents said number (like using binary, using 2’s complement for negative numbers, etc.) are not in the scope of those string formatting operations.
A good way to get at the actual representations of values in Python is the struct
module. For example, struct.pack("@i", -1)
returns the bytestring b'xffxffxffxff'
. Printing that bytestring in binary is left as an exercise to the reader.
PS: For numbers other than -1
, you may be surprised by the output of struct.pack
. The term you’ll want to look up is endianness, and the @
in my struct.pack
formatting string.
As @gspr said, formatting as base 2 doesn’t give you the actual representation. You can solve it by masking the negative integer, which has infinitely many leading 1s for the purposes of bitwise operations, down to 32 bits:
return f"{num_bits & 0xffff_ffff:032b}"