I a trying to convert a decimal number into a 17-bit binary number and add underscore as a separator in it. I am using the following code -
id = 18
get_bin = lambda x, n: format(x, 'b').zfill(n)
bin_num = get_bin(id, 17)
The output I am getting is in the form of -
00000000000010010
I am trying to get the following output -
0_0000_0000_0001_0010
How can I get it?
Using good'ol pal, Python's Format Specification Mini-Language
id = 18
width = 17
bin_num = format(id, '0{}_b'.format(width+3))
print(bin_num)
#0_0000_0000_0001_0010
One way:
import textwrap
result = '_'.join(textwrap.wrap(bin_num[::-1], 4))[::-1]
'0_0000_0000_0001_0010'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With