-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyBytes.py
60 lines (49 loc) · 1.86 KB
/
myBytes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import logging
from typing import Optional
from attr import define
'''
Helper class to improve bytes handling
This was not made properly, it has low performance.
'''
@define( init=True )
class Bytes:
# instance variables:
value: bytes = bytes() # stored in big endian
@classmethod
def fromLazyIntLE(cls, input_: int, LEndian: bool = True, size: Optional[int] = None):
if size is None:
size = len(bytearray.fromhex(str(hex(input_)[2:]))) # "2:" to remove str "0x"
if LEndian:
ba = input_.to_bytes(length=size, byteorder="little")
else:
ba = input_.to_bytes(length=size, byteorder="big")
return cls.fromBytes(ba)
def __sizeof__(self):
return len(self.value)
@classmethod
def fromBytes(cls, value: bytes, useSizePowerOfTwo: bool = True):
#TODO check
print("untested 151903")
if len(value) == 0: raise ValueError
if useSizePowerOfTwo:
while len(value) not in [1, 2, 4, 8, 16, 32, 64]:
logging.debug("warning: extending byte array, only works if size is a power of two")
if len(value) > 64: raise NotImplementedError
value = bytes.fromhex("00") + value
return cls(value)
def __int__(self):
return int.from_bytes(self.value , byteorder="big")
@classmethod
def fromStrLE(cls, input_: str, LEndian: bool = True):
input_=input_.replace(" ", "")
ba = bytearray.fromhex(input_)
if LEndian: ba.reverse()
return cls.fromBytes(ba,False)
def __index__(self): # this is to override __hex__
return int(self.value)
def printableBytes(input_: bytes , add0x: bool = False) -> str:
data:str = input_.hex()
if not add0x:
return data
else:
return "0x" + data