How to split 16-bit unsigned integer into array of bytes in python? -
I need to divide a 16-bit signed integer into an array of bytes (i.e. array.array ('B')
) in Python
For example:
& gt; & Gt; & Gt; Reg_val = 0xABCD [Insert Python Magic]> gt; & Gt; & Gt; Print ("0x% X"% myarray [0]) 0xCD & gt; & Gt; & Gt; Print ("0x% X"% myarray [1]) 0xAB
The way I am currently doing it is very easy, so some are very easy:
& gt; & Gt; & Gt; Import structure & gt; & Gt; & Gt; Import array & gt; & Gt; & Gt; Reg_val = 0xABCD> & Gt; & Gt; Reg_val_msb, reg_val_lsb = struct.unpack ("& lt; BB", struct.pack ("& lt; H", (0xFFFF and reg_val))) & Gt; & Gt; Myarray = array.array ('B')> gt; & Gt; & Gt; Myarray.append (reg_val_msb) & gt; & Gt; & Gt; Myarray.append (reg_val_lsb)
Is there a better / more efficient / more python way to accomplish the same thing?
(using Python 3 here, there are some naming variations in 2)
Well before, you can leave everything as bytes
. It is absolutely valid:
reg_val_msb, reg_val_lsb = struct.pack ('<', 0xABCD)
bytes
Allows for "unpacking the tubes" (not related to struct.unpack
, tupl unpacking is used on all pythons). And bytes
is an array of bytes, which you can access through the index.
b = struct.pack (& lt; H ', 0xABCD) b [0], b [1] out [52]: (205, 171)
< / Pre>If you really want to get it in an
array array ('b')
, it's still not easy:ary = Array ('b', struct.pack ('& lt; h', 0xABCD)) # ary = array ('b', [205, 171]) print ("0x% X"% ary [0]) # 0xCD
Comments
Post a Comment