Move the bits of an int

1

I want to move the bits that make up a int using the operator << without the number of bits that make up the integer increasing. For example:

i = 5 #101 en binario
i = i << 2
print bin(i) 

I want the bits that make up i to acquire the 100 corresponding to moving the 3 initial bits. However, what happens is that it adds two zeros to the right, with which the bits of i are finally 10100 .

I understand that this happens because the binary displacement is analogous to multiplying, hence I add the zeros, but I do not know how to keep the number of bits I want.

    
asked by Kurosh D. 25.11.2017 в 00:26
source

2 answers

3

If you want to eliminate unnecessary bits you should use the operation and with the appropriate mask:

i = 5 #101 en binario
i = (i << 2) & 7 # 7 es 00111
print(bin(i))

Output:

0b100
    
answered by 25.11.2017 / 00:40
source
1

You have to apply what is known as a mask. Example in C:

int main()
{
    int i = 5;
    i = i << 2; // 10100
    i = i & 7; // 10100 & 00111 => 100

    printf("Valor de i: %d.", i);

    return 0;
}

Exit : "Value of i: 4".

    
answered by 25.11.2017 в 00:38