dec8/dcd/bit.py
2019-10-28 03:48:31 +01:00

58 lines
1.1 KiB
Python

#! /usr/bin/env python3
# encoding: utf-8
# ----------------------------------------------------------------
class Bitfield:
def __init__(self):
self.value = 0
self.length = 0
def shift_in(self, value, length):
self.value <<= length
self.value |= value
self.length += length
def dump(self, align=True):
value = self.value
length = self.length
pad = (8 - (length % 8)) % 8
value <<= pad
length += pad
Bs = []
for i in range(length // 8):
Bs.insert(0, value & 0xff)
value >>= 8
return bytes(Bs)
# ----------------------------------------------------------------
def raw_to_hex(raw, separator=" "):
"""
Converts a bytearray (or bytes) into its textual hexadecimal representation.
"""
output = []
for o in raw:
output.append(hex(o)[2:].zfill(2))
return separator.join(output)
def hex_to_raw(text, separator=" "):
"""
Converts a hexadecimal representation of a byte array into a bytearray.
"""
output = []
text = text.replace(separator, "")
for i in range(len(text)//2):
output.append(int(text[2*i:2*i+2], 16))
return bytearray(output)