[Need help] How to use snap7.util.get_int? #448
-
|
I'm new to snap7. I read the document https://python-snap7.readthedocs.io/en/latest/API/client.html, and find use What needs to do if I would like to read a db_area as int type, I find I tried: import snap7
b = bytearray(b"\x01\x18")
i = snap7.util.get_int(b,0) #280
b = bytearray(b"\x01\x18\x01")
i = snap7.util.get_int(b,0) #280
b = bytearray(b"\x01\x18\x01")
i = snap7.util.get_int(b,1) #6145That seems mean Is there a better way to read int from a db area. Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
|
I fond the function Is this function aims to convert bytearray to a list result? Or theres another function to do so. Here's a function to convert the whole bytearray_ to int list. def get_array_int(bytearray_: bytearray) -> List[int]:
if len(bytearray_) % 2 == 1: return []
result = []
for i in range(0, len(bytearray_), 2):
integer = (bytearray_[i] << 8) + bytearray_[i+1]
result.append(integer)
return result |
Beta Was this translation helpful? Give feedback.
-
|
Hi, @tom9672
It's a typo. Thanks for pointing this out.
If you want to convert a bytearray to integers, you can use the built-in struct module. Here is an example: >>> import struct
>>> bytearray_ = b'\x00\x01\x00\x16\x01M\x11\\09' # (1, 22, 333, 4444, 12345)
>>> tuple_of_ints = struct.unpack('>5H', bytearray_)
>>> print(tuple_of_ints)
(1, 22, 333, 4444, 12345)
>>> a, b, c, d, e = struct.unpack('>5H', bytearray_) # unpack to variables
>>> print(a, b, c, d, e)
1 22 333 4444 12345 |
Beta Was this translation helpful? Give feedback.
-
|
Closing as answered. The documentation typo was acknowledged, and the use of |
Beta Was this translation helpful? Give feedback.
Closing as answered. The documentation typo was acknowledged, and the use of
struct.unpackfor batch integer conversion was explained.