Skip to content

Commit 91da06d

Browse files
committed
fix issue #101
1 parent 5d7f45d commit 91da06d

File tree

2 files changed

+18
-6
lines changed

2 files changed

+18
-6
lines changed

snap7/util.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -128,24 +128,28 @@ def set_bool(_bytearray, byte_index, bool_index, value):
128128
_bytearray[byte_index] -= index_value
129129

130130

131-
def set_int(_bytearray, byte_index, _int):
131+
def set_int(bytearray_, byte_index, _int):
132132
"""
133133
Set value in bytearray to int
134134
"""
135135
# make sure were dealing with an int
136136
_int = int(_int)
137137
_bytes = struct.unpack('2B', struct.pack('>h', _int))
138-
_bytearray[byte_index:byte_index + 2] = _bytes
138+
bytearray_[byte_index:byte_index + 2] = _bytes
139+
return bytearray_
139140

140141

141-
def get_int(_bytearray, byte_index):
142+
def get_int(bytearray_, byte_index):
142143
"""
143144
Get int value from bytearray.
144145
145146
int are represented in two bytes
146147
"""
147-
data = _bytearray[byte_index:byte_index + 2]
148-
value = struct.unpack('>h', struct.pack('2B', *data))[0]
148+
data = bytearray_[byte_index:byte_index + 2]
149+
data[1] = data[1] & 0xff
150+
data[0] = data[0] & 0xff
151+
packed = struct.pack('2B', *data)
152+
value = struct.unpack('>h', packed)[0]
149153
return value
150154

151155

test/test_util.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import unittest
22
import re
33

4-
from snap7 import util
4+
from snap7 import util, snap7types
55

66

77
test_spec = """
@@ -72,6 +72,14 @@ def test_set_int(self):
7272
row['ID'] = 259
7373
self.assertEqual(row['ID'], 259)
7474

75+
def test_set_int_roundtrip(self):
76+
DB1 = (snap7types.wordlen_to_ctypes[snap7types.S7WLByte]*4)()
77+
78+
for i in range(-(2**15)+1, (2**15)-1):
79+
util.set_int(DB1, 0, i)
80+
result = util.get_int(DB1, 0)
81+
self.assertEqual(i, result)
82+
7583
def test_get_int_values(self):
7684
test_array = bytearray(_bytearray)
7785
row = util.DB_Row(test_array, test_spec, layout_offset=4)

0 commit comments

Comments
 (0)