Use the format() function:
>>> format(14, '#010b')
'0b00001110'
The format() function simply formats the input following the Format Specification mini language. The # makes the format include the 0b prefix, and the 010 size formats the output to fit in 10 characters width, with 0 padding; 2 characters for the 0b prefix, the other 8 for the binary digits.
This is the most compact and direct option.
If you are putting the result in a larger string, use an formatted string literal (3.6+) or use str.format() and put the second argument for the format() function after the colon of the placeholder {:..}:
>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'
As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using format():
>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format") # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193
But I'd use that only if performance in a tight loop matters, as format(...) communicates the intent better.
If you did not want the 0b prefix, simply drop the # and adjust the length of the field:
>>> format(14, '08b')
'00001110'
Answer from Martijn Pieters on Stack OverflowUse the format() function:
>>> format(14, '#010b')
'0b00001110'
The format() function simply formats the input following the Format Specification mini language. The # makes the format include the 0b prefix, and the 010 size formats the output to fit in 10 characters width, with 0 padding; 2 characters for the 0b prefix, the other 8 for the binary digits.
This is the most compact and direct option.
If you are putting the result in a larger string, use an formatted string literal (3.6+) or use str.format() and put the second argument for the format() function after the colon of the placeholder {:..}:
>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'
As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using format():
>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format") # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193
But I'd use that only if performance in a tight loop matters, as format(...) communicates the intent better.
If you did not want the 0b prefix, simply drop the # and adjust the length of the field:
>>> format(14, '08b')
'00001110'
>>> '{:08b}'.format(1)
'00000001'
See: Format Specification Mini-Language
Note for Python 2.6 or older, you cannot omit the positional argument identifier before :, so use
>>> '{0:08b}'.format(1)
'00000001'
Convert decimal to binary in python - Stack Overflow
Converting from decimal to binary in Python
How to convert an integer to binary in Python and pad with leading zeros? - Ask a Question - TestMu AI Community
Convert decimal input to 8 bit binary
In Python, the 0b binary representation notation is just another way of writing integers. So there is no difference, for example, between 0b11 and 0b0011 - they both represent the integer 3.
Also, base64 encoding is designed for input data in 8-bit groups. The encoding is designed so that the decoder may determine exactly the number of bytes that were used in the original data. However, this granularity extends only to 8-bit groups and does not extend down to the actual bit level.
One approach might be to encode your data with the first byte representing the number of bits, and then the following bytes representing the actual bits themselves. Your decoder could use this information to extract the exact number of bits you originally stored (with leading or trailing zeros, if you like).
Both x and y hold integer values, you just choose to use 0b binary literals to define them.
If you want to combine the two into z, you can easily do so using a shifting operation and binary bitwise operations:
>>> x = 0b00010101010
>>> y = 0b1110000
>>> z = (x << 7) | y
>>> bin(z)
'0b101010101110000'
Do note that python does not track how many bits 'precision' you want to keep on such values; you defined y with 7 bits of information, so I had to shift x to the left 7 times to make room for y. You'd have to track this information yourself.
Your next problem is representing data as base64 as this format requires you to provide it with bytes only. That's chunks of 8 bits of binary data. This means you'll have to align your bits to the 8-bit boundaries and then turn these into bytes (e.g. strings). You won't be able to get around that, I'm afraid.
I'd use the struct module for that, it lets you pack integers and other data-types into bytes with ease:
>>> import struct
>>> struct.pack('>H', x)
'\x00\xaa'
>>> struct.pack('>H', x).encode('base64')
'AKo=\n'
In the above example I've packed the 11-bits x variable as an unsigned short (using the little-endian standard C format), resulting in 2 bytes of information, then encoded that to base64.
The reverse then requires decoding from base64, then an unpack operation:
>>> foo = struct.unpack('>H', 'AKo=\n'.decode('base64'))[0]
>>> bin(foo)
'0b10101010'
Again, Python doesn't track how many bits of information is important to you, you'll have to track that explicitly.
all numbers are stored in binary. if you want a textual representation of a given number in binary, use bin(i)
>>> bin(10)
'0b1010'
>>> 0b1010
10
Without the 0b in front:
"{0:b}".format(int_value)
Starting with Python 3.6 you can also use formatted string literal or f-string, --- PEP:
f"{int_value:b}"
Would someone be willing to help me (total beginner) understand how this converts decimal values to binary? Maybe just by explaining what happens line by line?
def dec2bin(n):
if n > 1:
dec2bin(n//2)
print(n % 2, end="")It's just not intuitive at all for me :/
Any help would be greatly appreciated!
Hi all i'm very new to coding (a few weeks) and Python and was wondering if there is a way to get an input of a decimal number and convert it to 8 bit binary. Currently using the Thonny IDE
So i have binary number: 1000000111100011111
How do i add five zero’s at the beginning?