77 lines
1.4 KiB
Python
77 lines
1.4 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)
|
|
|
|
def raw_to_bcd(raw):
|
|
"""
|
|
Decodes a bytearray (or bytes) to an integer as BCD.
|
|
"""
|
|
|
|
sum = 0
|
|
order = 1
|
|
|
|
for byte in reversed(raw):
|
|
sum += (byte & 0x0f) * order
|
|
order *= 10
|
|
sum += (byte >> 4) * order
|
|
order *= 10
|
|
|
|
return sum
|
|
|
|
def hex_to_bcd(text):
|
|
return raw_to_bcd(hex_to_raw(text))
|