0

Let's say I have three unsigned integers, A, B, and C, and I know the maximum values of each. Both A and B are less than 214, and C is less than 24. Since 14 + 14 + 4 = 32, I should be able to store these three integers in 32 bits, right?

If so, how can I do this in python? Struct.pack only appears to support byte-sized registers, so I would be limited to 'HHB', which is 40 bits (8 more than I need). Can this be done, or am I missing some fundamental concepts here?

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
Ben Davis
  • 13,112
  • 10
  • 50
  • 65
  • Relevant, though I don't know whether the answers are still up to date: http://stackoverflow.com/questions/39663/what-is-the-best-way-to-do-bit-field-manipulation-in-python – user2357112 Apr 09 '15 at 02:47
  • Could you do it yourself using bitwise operators? – 101 Apr 09 '15 at 03:10
  • @figs I suppose I could, I just don't work with bitwise often enough to know the solution. I did just find a library called bitstring that seems to do what I want. – Ben Davis Apr 09 '15 at 03:31

2 Answers2

0

The library sounds like the way to go, but just for fun with bitwise operations:

a_in, b_in, c_in = 15220, 9021, 9
a_bits, b_bits, c_bits = 14, 14, 4

packed = a_in << b_bits + c_bits | b_in << c_bits | c_in

a_out = (packed & 2 ** a_bits - 1 << b_bits + c_bits) >> b_bits + c_bits
b_out = (packed & 2 ** b_bits - 1 << c_bits) >> c_bits
c_out =  packed & 2 ** c_bits - 1

print packed    # 3989976025 = 11101101110100100011001111011001
print a_out     # 15220      = 11101101110100
print b_out     # 9021       =               10001100111101
print c_out     # 9          =                             1001
101
  • 8,514
  • 6
  • 43
  • 69
0

Pack it yourself with bit operators:

(A<<18)|(B<<4)|C

Then use struct.pack on the 32-bit result.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251