-
Notifications
You must be signed in to change notification settings - Fork 8
/
binman.py
executable file
·57 lines (46 loc) · 1.69 KB
/
binman.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
import binascii
def byte_to_binary(n):
""" 5 -> "00000101" """
return ''.join(str((n & (1 << i)) and 1) for i in reversed(range(8)))
def hex_to_binary(h):
"""" "1f" -> "00011111" """
return ''.join(byte_to_binary(ord(b)) for b in binascii.unhexlify(h))
def ascidxFromBites(in_stream):
str_len = len(in_stream) // 8
asc_idx = 0
for x in xrange(0, str_len):
bytetmp = int(in_stream[x * 8:(x * 8) + 8], 2)
if 31 < bytetmp < 127: # and bytetmp != 44 and bytetmp != 96 and bytetmp != 39 and bytetmp != 92:
asc_idx += 1
if str_len > 0:
return (asc_idx * 100) // str_len
else:
return 0
def strFromBites(in_stream):
""" "01001001010101000100010001010011" -> "ITDS" """
outasc = ""
for x in xrange(0, len(in_stream) // 8):
bytetmp = int(in_stream[x * 8:(x * 8) + 8], 2)
if 31 < bytetmp < 127: # and bytetmp != 44 and bytetmp != 96 and bytetmp != 39 and bytetmp != 92:
outasc += chr(bytetmp)
else:
outasc += " "
return outasc
def hexFromBites(in_stream):
""" "01001001010101000100010001010011" -> "49:54:44:53:" """
outhex = ""
for x in xrange(0, len(in_stream) // 8):
bytetmp = int(in_stream[x * 8:(x * 8) + 8], 2)
outhex = outhex + format(bytetmp, '02X') + ":"
return outhex
def bitesFromHex(in_hex):
""" "0A:FF:10:AA:12" -> "0000101011111111000100001010101000010010" """
outbin = ""
if in_hex[0] == ":":
in_hex = in_hex[1:]
if len(in_hex) % 3 != 0:
in_hex += ":"
for x in xrange(0, len(in_hex) // 3):
hex_chunk = in_hex[x * 3:(x * 3) + 2]
outbin = outbin + hex_to_binary(hex_chunk)
return outbin