dawenzi098 dawenzi098 - 3 months ago 7
Python Question

python '<<' operator not work, any buildin module about it

I am using python to do some work which need I do some math like this

c = bitshift(a, b); %this is matlab code which just shift c to left b bits.

if a = '1111111' then after this bitshift, it should be

c = '1111110'


I did some research, '<<' operator did similar thing but not same.

I did python code like this:

a = 255
print a
print '{0:b}'.format(a)
b = a <<1


the output is

11111111
111111110


instead of shift one bit to left, it adds one '0' at the end.

are there any build in things that I can use to do the same thing with matlab?

or I have to write my own function to do it.

Answer

You are doing a bit shift. Keep in mind that 11111111 is 000...011111111 (usually 32 bits for integer). then:

0000000011111111
0000000111111110
0000001111111100

and so on, but the computer doesn't print the zeros in the beginning. if you want to limit your number to 8 bits, use the & (bitwise and) operator: var & 255, that will bring only the most right 8 bits.

Comments