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.
The Python bitwise left-shift operator x << n shifts the binary representation of integer x by n positions to the left. For a positive integer, it inserts a 0 bit on the right and shifts all remaining bits by one position to the left.
Python bitwise left shift operator shifts the left operand bits towards the left side for the given number of times in the right operand. In simple terms, the binary number is appended with 0s at the end.
Use Python bin to Convert Int to Binary The Python bin() function is short for binary and allows us to convert an integer to a binary string, which is prefixed by '0b' .
Logical bit shifting may be useful for multiplying or dividing unsigned integers by powers of two. For example, if the value "0001" or "1" is shifted left, it becomes "0010" or "2," shifted to the left again it becomes "0100," or "4." Shifting to the right has an opposite effect of dividing the value by two per shift.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With