简体   繁体   中英

Converting a binary formatted string (with leading zeros) to an integer and back again

I have converted 4 characters ATCG in to binary format ie

00 replacing A 
11 replacing T 
10 replacing C 
01 replacing G 

So a character string

AGAGAGAGTGATAGA 

after conversion will look like

001000100010001011100011001000

Once I get this value I convert this binary in to its corresponding integer ie

143177928.

The issue is, when I want to get back to binary again, it gives me

0b1000100010001011100011001000

which is not the correct representation of original character string because it omits all the zeros from far left after 1.

So I have written a method implementing binary conversion and I know how long the binary string should be. So in the end I just remove 0b from the returned binary and append 0s in the far left ie

#zeros = length of original binary - length of returned binary (0b removed) 

Is there any better way of doing this conversion??

I am coding this in python.

You can append a flag bit after the MSB to protect all the leading zeros.

Step 1: Conversion

Add a single "flag" bit at the end and convert your bit string.

In [6]: converted_str = '001000100010001011100011001000'

In [9]: num = int('1' + converted_str, 2)

In [10]: num
Out[10]: 1216919752

Step 2: Re-conversion

Use the format method to convert your number back to a bit string, while stripping off the first "flag" bit.

In [12]: reconverted_str = format(num, 'b')[1:]

In [13]: reconverted_str
Out[13]: '001000100010001011100011001000'

Use '{0:0{1}b}'.format(num, num_digits)

This will add leading 0's until the number is num_digits . The 'b' specifies that num should be converted to binary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM