diff --git a/dcd/__init__.py b/dcd/__init__.py index 2df4d07..6755f9a 100644 --- a/dcd/__init__.py +++ b/dcd/__init__.py @@ -3,5 +3,6 @@ from . import argv from . import aux +from . import bit from . import cfg from . import dt diff --git a/dcd/aux.py b/dcd/aux.py index c33f900..ac46a9a 100644 --- a/dcd/aux.py +++ b/dcd/aux.py @@ -18,6 +18,20 @@ def flatten_dict(root, glue=" ", prefix=[]): # ---------------------------------------------------------------- +def clamp(A, low, high): + """ + Clamps integer A to + """ + + if A < low: + return low + elif A > high: + return high + else: + return A + +# ---------------------------------------------------------------- + import random PASSPHRASE_VOWELS = "aeiuAEU" @@ -50,34 +64,6 @@ def hash_password(p, hexdigest=True): # ---------------------------------------------------------------- -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) - -# ---------------------------------------------------------------- - class DeleteOverlay: pass diff --git a/dcd/bit.py b/dcd/bit.py new file mode 100644 index 0000000..5a610ec --- /dev/null +++ b/dcd/bit.py @@ -0,0 +1,58 @@ +#! /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)