[Python] Python Bit Shifting

Discussão em 'Python' iniciado por Stack, Setembro 17, 2025.

  1. Stack

    Stack Membro Participativo

    Assume I have a 1 source variable (int) which is 10 bits long. Let's call it src. I have 2 destination variables (int) which are 8 bits long namely byte1 and byte2.

    MSB LSB
    src 0 1 2 3 4 5 6 7 8 9 --- bit numbers
    1 1 0 0 1 0 1 1 1 0 --- assigned bits
    value 814



    What I would like to do is copy the first 8 bits from src to byte1 and the last 2 bits from src to the MSB of byte2 so byte1 and byte2 should contain the following:

    MSB LSB
    byte1 0 1 2 3 4 5 6 7 --- bit numbers
    1 1 0 0 1 0 1 1
    value 203



    I can do this with byte1 = src >> 2 which works perfectly as intended

    MSB LSB
    byte2 0 1 2 3 4 5 6 7
    1 0 0 0 0 0 0 0
    value 128



    Where I am stuck is with byte2. I have tried creating a mask for the last 2 bits and ANDing the source and mask together and then ORing the extracted bits.

    Continue reading...

Compartilhe esta Página