7

I have an integer input from a text file which I need to convert to binary and do a left bit shift by 12 places.

So, if my number is 6. It is 110 in binary. My final output should be 110000000000000, bit shifted by 12 places.

I tried:

i = 6
h = int(bin(i)[2:])<<12

But, this gives the wrong output. The problem is bin(i) returns a string, so I had to convert it into int but then using the shift operator shifts the integer and not the binary.

1
  • 1
    Without indication, that i or h are actually used afterwards, I would recommend to drop one of these variable. Note also, that "{:b}".format(i) creates the binary representation of i without the leading 0b you remove afterwards. Commented Oct 2, 2018 at 10:06

2 Answers 2

6

You can do the bit shift before converting to binary, since the bit shifting doesn't care about the base of your integer (bit shifting is by definition done in the base of 2).

i = 6 << 12
answer = bin(i)[2:]

Edit: Alternative binary conversion from @guidot

i = 6 << 12
answer = "{:b}".format(i)

Additional conversions

Just for the fun of it, here's some other ways to bit shift a number:

i = 6 * (2**12) # This will convert into 6 * 2^12
answer = "{:b}".format(i)

A bit shift will double the numbers value, so by multiplying the bitshift with the power two we achieve the same thing:

> print(6 << 12)
24576
> print(6 * 2**12)
24576

It's generally better to use bit shift if you know you only want to double the value.

You can also convert it to binary and then add 13 trailing zeroes, a funky way to achieve the same functionality:

i = 6 # Notice: No operation here this time
answer = "{:b}".format(i) + ('0' * 12)

Maybe not recommended to use the last method, but it illustrates how (left) bit shifting works.

Sign up to request clarification or add additional context in comments.

Comments

-1

I found a way to do it.

h = int((bin(i<<12)[2:]), 2)

1 Comment

The back and forth conversion looks more than cumbersome.

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.