-
Notifications
You must be signed in to change notification settings - Fork 0
/
byteprint.py
60 lines (36 loc) · 1.52 KB
/
byteprint.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
def chunks(seq, chunk_size):
for i in range(0, len(seq), chunk_size):
yield seq[i: i + chunk_size]
def get_bytes_str(bytes_, max_length=None, sep=' '):
if isinstance(bytes_, int):
return '0x' + hex(bytes_).lstrip('0x').upper()
if max_length is None or len(bytes_) <= max_length:
return sep.join(map('{:02x}'.format, bytes_)).upper()
return sep.join(map('{:02x}'.format, bytes_[0:max_length])).upper() + '...'
def to_mac_address(bytes_):
if len(bytes_) != 6:
raise ValueError('Invalid bytes amount for mac')
return ':'.join(map('{:02x}'.format, bytes_)).upper()
def to_hexed_int(val, length=None):
if length is None:
return '0x' + hex(val).lstrip('0x').upper()
return '0x' + hex(val).lstrip('0x').zfill(length).upper()
def to_ipv4_address(bytes_):
if len(bytes_) != 4:
raise ValueError('Invalid bytes amount for ipv4 address')
return '.'.join(map(str, bytes_))
def to_ipv6_address(bytes_):
if len(bytes_) != 16:
raise ValueError('Invalid bytes amount for ipv6 address')
return ':'.join(map(lambda x: get_bytes_str(x, sep='').zfill(4), chunks(bytes_, 2)))
def to_binary(bytes_):
if isinstance(bytes_, bytes):
return ''.join(map(lambda x: bin(x).lstrip('0b'), bytes_))
if isinstance(bytes_, int):
return bin(bytes_).lstrip('0b')
raise ValueError
def to_hex_dump(bytes_, rows=16, tab=''):
dump = ''
for chunk in chunks(bytes_, rows):
dump += f'{tab}{get_bytes_str(chunk)}\n'
return dump