Convert integer to binary and then do a left bit shift in python
Asked Answered
B

2

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.

Brough answered 2/10, 2018 at 9:39 Comment(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.Amphimacer
M
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.

Mozell answered 2/10, 2018 at 9:41 Comment(0)
B
-1

I found a way to do it.

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

Brough answered 2/10, 2018 at 9:40 Comment(1)
The back and forth conversion looks more than cumbersome.Amphimacer

© 2022 - 2024 — McMap. All rights reserved.