From b6d57a88f0a8ff62152e5a2148f77e10bf7bccbe Mon Sep 17 00:00:00 2001 From: David Kerkeslager Date: Sat, 24 Sep 2016 17:34:14 -0400 Subject: [PATCH] Added serialization and deserialization for signed integers --- serial/binary.py | 12 ++++++++++++ serial/test_binary.py | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/serial/binary.py b/serial/binary.py index c4693db..d362092 100644 --- a/serial/binary.py +++ b/serial/binary.py @@ -10,6 +10,10 @@ TAG_UINT8 = 0x03 TAG_UINT16 = 0x04 TAG_UINT32 = 0x05 TAG_UINT64 = 0x06 +TAG_INT8 = 0x10 +TAG_INT16 = 0x11 +TAG_INT32 = 0x12 +TAG_INT64 = 0x13 TaggedObject = collections.namedtuple( 'TaggedObject', @@ -45,6 +49,10 @@ _TAGS_TO_SERIALIZERS = { TAG_UINT16: _make_struct_serializer('H'), TAG_UINT32: _make_struct_serializer('I'), TAG_UINT64: _make_struct_serializer('Q'), + TAG_INT8: _make_struct_serializer('b'), + TAG_INT16: _make_struct_serializer('h'), + TAG_INT32: _make_struct_serializer('i'), + TAG_INT64: _make_struct_serializer('q'), } def serialize(to): @@ -76,6 +84,10 @@ _TAGS_TO_PARSERS = { TAG_UINT16: _make_struct_deserializer(TAG_UINT16, 'H'), TAG_UINT32: _make_struct_deserializer(TAG_UINT32, 'I'), TAG_UINT64: _make_struct_deserializer(TAG_UINT64, 'Q'), + TAG_INT8: _make_struct_deserializer(TAG_INT8, 'b'), + TAG_INT16: _make_struct_deserializer(TAG_INT16, 'h'), + TAG_INT32: _make_struct_deserializer(TAG_INT32, 'i'), + TAG_INT64: _make_struct_deserializer(TAG_INT64, 'q'), } def deserialize(b): diff --git a/serial/test_binary.py b/serial/test_binary.py index e72447f..0463dda 100644 --- a/serial/test_binary.py +++ b/serial/test_binary.py @@ -10,6 +10,18 @@ EXAMPLE_REPRESENTATIONS = [ (binary.TAG_UINT16, 7, b'\x04\x00\x07'), (binary.TAG_UINT32, 7, b'\x05\x00\x00\x00\x07'), (binary.TAG_UINT64, 7, b'\x06\x00\x00\x00\x00\x00\x00\x00\x07'), + (binary.TAG_INT8, 7, b'\x10\x07'), + (binary.TAG_INT16, 7, b'\x11\x00\x07'), + (binary.TAG_INT32, 7, b'\x12\x00\x00\x00\x07'), + (binary.TAG_INT64, 7, b'\x13\x00\x00\x00\x00\x00\x00\x00\x07'), + (binary.TAG_UINT8, 254, b'\x03\xfe'), + (binary.TAG_UINT16, 65534, b'\x04\xff\xfe'), + (binary.TAG_UINT32, 4294967294, b'\x05\xff\xff\xff\xfe'), + (binary.TAG_UINT64, 18446744073709551614, b'\x06\xff\xff\xff\xff\xff\xff\xff\xfe'), + (binary.TAG_INT8, -2, b'\x10\xfe'), + (binary.TAG_INT16, -2, b'\x11\xff\xfe'), + (binary.TAG_INT32, -2, b'\x12\xff\xff\xff\xfe'), + (binary.TAG_INT64, -2, b'\x13\xff\xff\xff\xff\xff\xff\xff\xfe'), ] class SerializeTests(unittest.TestCase): -- 2.20.1