added hex methods

This commit is contained in:
S Groesz 2021-04-13 06:41:39 +00:00
parent 66aa7ee915
commit c63d2dd4bb
3 changed files with 39 additions and 0 deletions

View File

@ -921,6 +921,12 @@ class Bits:
ret.append(Bit(b))
return ret
def hex(self):
"""
Return the hex-string representation of self
"""
return bytes(self).hex()
class Bytes:
"""
@ -1125,6 +1131,15 @@ class Bytes:
chop += 1
return ret + bin(i)[chop:]
def hex(self, sep=None, bytes_per_sep=1):
"""
Return the hex-string representation of self
"""
if sep is None or bytes_per_sep is None or bytes_per_sep == 0:
return bytes(self).hex()
else:
return bytes(self).hex(sep=sep, bytes_per_sep=bytes_per_sep)
@property
def bytes(self):
return bytes(self)

View File

@ -8,6 +8,7 @@ class TestBits(TestCase):
{"bytes": b'\x7f',
"str": "01111111",
"int": 127,
"hex": "7f",
"reverse": 254,
"bitsObject": Bits(127),
"list": [Bit(0),
@ -23,6 +24,7 @@ class TestBits(TestCase):
{"bytes": b'\xcf',
"str": "11001111",
"int": 207,
"hex": "cf",
"reverse": 243,
"bitsObject": Bits(207),
"list": [1, 1, 0, 0, 1, 1, 1, 1]
@ -30,6 +32,7 @@ class TestBits(TestCase):
{"bytes": b'{',
"str": "01111011",
"int": 123,
"hex": "7b",
"reverse": 222,
"bitsObject": Bits(123),
"list": ["0", "1", "1", "1", "1", "0", "1", "1"]
@ -38,6 +41,7 @@ class TestBits(TestCase):
{"bytes": b'<',
"str": "00111100",
"int": 60,
"hex": "3c",
"reverse": 60,
"bitsObject": Bits(60),
"list": [False,
@ -53,6 +57,7 @@ class TestBits(TestCase):
{"bytes": b'>',
"str": "00111110",
"int": 62,
"hex": "3e",
"reverse": 124,
"bitsObject": Bits(62),
"list": [0,
@ -68,6 +73,7 @@ class TestBits(TestCase):
{"bytes": b'=',
"str": "00111101",
"int": 61,
"hex": "3d",
"reverse": 188,
"bitsObject": Bits(61),
"list": [True, 1, 1, True, Bit(0), Bit(1)]
@ -101,6 +107,12 @@ class TestBits(TestCase):
with self.subTest("testcase[\"int\"]: " + str(testcase["int"])):
self.assertEqual(int(testcase["bitsObject"]), testcase["int"])
def test_hex(self):
"""Test conversion to hex"""
for testcase in self.testObjects:
with self.subTest("testcase[\"hex\"]: " + str(testcase["hex"])):
self.assertEqual(testcase["bitsObject"].hex(), testcase["hex"])
def test_str(self):
"""Test string representation"""
for testcase in self.testObjects:

View File

@ -91,6 +91,18 @@ class TestBytes(TestCase):
with self.assertRaises(TypeError, msg="Bytes(\"1234\")"):
Bytes("1234")
def test_hex(self):
"""
Test conversion to hex string
"""
with self.subTest("Test hex() function"):
self.assertEqual(Bytes(1234).hex(), "04d2",
f"Bytes(1234).hex() == '04d2'")
self.assertEqual(Bytes(1234).hex(":"), "04:d2",
f"Bytes(1234).hex(':') == '04:d2'")
self.assertEqual(Bytes(1234).hex(":", 1), "04:d2",
f"Bytes(1234).hex(':', 1) == '04:d2'")
def test_comparison_operators(self):
"""
Test the comparison operators with Bytes objects