简体   繁体   中英

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

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.

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.

I found a way to do it.

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

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