confusion in left shift operator in python

bit-manipulation, python

Solution

You'd mask the resulting value, with `&` bitwise AND:

mask = 2 ** 16 - 1
k = (i << j) & mask

Here `16` is your desired bit width; you could use `i.bit_length()` to limit it to the minimum required size of `i`, but that'd mean that any left shift would drop bits.

The mask forms a series of `1` bits the same width as the original value; the `&` operation sets any bits to 0 outside of these:

>>> 0b1010 & 0b111
2
>>> format(0b1010 & 0b111, '04b')
'0010'

Some side notes:

- You are left shifting, not right shifting.

You appear to have forgotten to a `d` in your debug print:

print "%d left shift %d gives" % (i,j)

There was a lone `%` there that combined with the `g` for `gives` to make `%g` (floating point formatting).

You can use:

def showbits(x):
    return format(x, '016b')

to format an integer to a 0-padded 16-character wide binary representation without the `0b` prefix.

Problem

I am trying to use left shift operator on the 16 bit binary representation of a integer Code written is below: ``` def showbits(x): return bin(x)[2:].zfill(16) i=5225 print "Decimal %d is same as binary" % (i) print showbits(i) for j in range(0,5,1): k=i<<j print "%d right shift % gives" % (i,j) print showbits(k) ``` Output: ``` Decimal 5225 is same as binary 0001010001101001 5225 right shift 0ives 0001010001101001 5225 right shift 1ives 0010100011010010 5225 right shift 2ives 0101000110100100 5225 right shift 3ives 1010001101001000 5225 right shift 4ives 10100011010010000 ``` The main problem is that when it is shifting the leading '1', it is not vanishing but it is increasing one more bit... Any solution for that?

Original source