Python – How to convert int to a binary string?
In Python, we can use bin()
or format()
to convert an integer into a binary string representation.
print(bin(1)) # 0b1
print(bin(-1)) # -0b1
print(bin(10)) # 0b1010
print(bin(-10)) # -0b1010
print("{0:b}".format(10)) # 1010
print("{0:#b}".format(10)) # 0b1010 , with 0b prefix
print("{0:b}".format(10).zfill(8)) # 00001010 , pad zero, show 8 bits
print(format(10, "b")) # 1010
print(format(10, "#b")) # 0b1010, with 0b prefix
print(format(10, "b").zfill(16)) # 0000000000001010, pad zero, show 16 bits
# with hex, oct bin
# int: 10; hex: a; oct: 12; bin: 1010
result = "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(10)
print(result)
# with 0x, 0o, or 0b as prefix:
# int: 10; hex: 0xa; oct: 0o12; bin: 0b1010
result = "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(10)
print(result)
# word6: 3F3C4109 00 1111110011110001 00000100 001001
# mot 7 : 95AAE46F 10 010101101010101110010001 101111
I want make binary with the 2 string in bold 00000100010101101010101110010001
and multoply by math.pow(2,-33)
When I do manualy with caractere 0b, it is Ok, but not in programme
s= Ob00000100010101101010101110010001
v= s * math.pow(2,-33
My question is how convert string to binary ?
how do i convert any numbers to binary not just 10 and 1.
Thank you. That was really helpful