Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add underscore as a separator in a binary number in Python

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?

like image 295
SG9 Avatar asked Jul 17 '26 07:07

SG9


2 Answers

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
like image 156
anurag Avatar answered Jul 20 '26 02:07

anurag


One way:

import textwrap
result = '_'.join(textwrap.wrap(bin_num[::-1], 4))[::-1]

output:

'0_0000_0000_0001_0010'
like image 45
Nk03 Avatar answered Jul 20 '26 03:07

Nk03



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!