1

I have converted 4 characters ATCG in to binary format i.e

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 i.e

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 i.e

#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.

2
  • yes, the problem is with your encoding scheme... any number of leading zeros is the same binary number. you can only 'zero pad' the number to a fixed length in a string representation Commented Jul 13, 2017 at 14:03
  • stackoverflow.com/questions/3252528/… Commented Jul 13, 2017 at 14:31

2 Answers 2

2

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'
Sign up to request clarification or add additional context in comments.

1 Comment

it works.. fewer steps than mine. Many thanks. lets see if we get any other ideas. :)
0

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.

3 Comments

this was in my original method from previous stack suggestions. but I think adding a single bit initially and stripping it in the end is more efficient. thanks for your suggestion anyways.
More efficient in what way?
that way I am not dependent on the length of string to figure out how many zeros I want. With above method I know I have to add and strip a single bit so I am kind of avoiding variables for length of string and leading zeros.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.