Search code examples
pythonpython-3.xintegerbitbitwise-operators

How does python perform bitwise operations to store three values ​in an int?


For example, if I have an int with a length of 32 bits, how do I store value A in the first 16 bits, then store value B in bits 17-24, and value C in bits 25-32? And how can I get these three values ​​out of an int?


Solution

  • Assuming that your values fit in the assigned bit counts, it's just a question of shifting them to make an int, and then unshifting and masking to get them back:

    A = 34945
    B = 49
    C = 233
    B_shift = 16
    C_shift = 24
    
    result = A + (B << B_shift) + (C << C_shift)
    print(result)
    
    resA = result & ((1 << B_shift) - 1)
    resB = (result >> B_shift) & ((1 << (C_shift - B_shift)) - 1)
    resC = result >> C_shift
    
    print(resA, resB, resC)