Replies: 2 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.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm new to snap7. I read the document https://python-snap7.readthedocs.io/en/latest/API/client.html, and find use
db_read(db_number: int, start: int, size: int) → bytearray
to read data from PLC, as the exampleclient.db_read(1, 10, 4) #bytearray(b'\x00\x00')
shows read db1 from 10 to 14, why the size result is 2? But another example at the top of this document, the size of read result isclient.db_read(1, 0, 4) #bytearray(b"\x00\x00\x00\x00")
and the read size is the same (4).What needs to do if I would like to read a db_area as int type, I find
snap7.util.get_int(bytearray_: bytearray, byte_index: int) → int
seems to convert bytearray to int.I tried:
That seems mean
get_int
takes 2 bytes as one int. Can I consider if I need to read 20 byte size if I need 10 int, and to convert these 20 bytes, I need to loop the bytearray and use 10 timesget_int
?Is there a better way to read int from a db area.
Thanks in advance!
Beta Was this translation helpful? Give feedback.
All reactions