forked from jevinskie/jevutils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhexer
executable file
·65 lines (59 loc) · 2.03 KB
/
hexer
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
61
62
63
64
65
#!/usr/bin/env python3
import argparse
import sys
from more_itertools import chunked
parser = argparse.ArgumentParser()
parser.add_argument("hex_bytes", metavar="HB", type=str, nargs="*", help="Hex byte")
parser.add_argument("-i", "--stdin", action="store_true", help="Get bytes from stdin")
parser.add_argument(
"-b", "--stdin-binary", action="store_true", help="Specify that stdin is raw bytes"
)
parser.add_argument(
"-r",
"--reverse",
action="count",
default=0,
help="Reverse byte order - can be repeated to invert option",
)
parser.add_argument(
"-c",
"--chunk",
type=lambda x: int(x, 0),
metavar="N",
help="Chunk ever N bytes during byte reversal",
)
parser.add_argument("-H", "--hex", action="store_true", help="Output a normalized hex string")
parser.add_argument(
"-x", "--hex-prefix", action="store_true", help="Output bytes seperated by ' 0x'"
)
parser.add_argument("-s", "--string", action="store_true", help="print escaped string literal")
parser.add_argument("-B", "--output-binary", action="store_true", help="print binary")
args = parser.parse_args()
if not args.stdin_binary:
if not args.stdin:
args.hex_bytes = [a.replace(",", "") for a in args.hex_bytes]
hex_bytes_str = "".join([hbs.removeprefix("0x") for hbs in args.hex_bytes])
else:
hba = [a.replace(",", "") for a in sys.stdin.read().split()]
hex_bytes_str = "".join([hbs.removeprefix("0x") for hbs in hba])
buf = bytes.fromhex("".join([hbs.removeprefix("0x") for hbs in hex_bytes_str]))
else:
buf = sys.stdin.buffer.read()
if bool(args.reverse % 2):
if args.chunk is not None:
rbuf = b""
for c in chunked(buf, args.chunk):
rbuf += bytes(c[::-1])
buf = rbuf
else:
buf = buf[::-1]
if args.string:
print(repr(buf)[1:])
if args.output_binary:
sys.stdout.buffer.write(buf)
elif not (args.hex or args.hex_prefix):
sys.stdout.buffer.write(buf)
elif args.hex_prefix:
print(" ".join([f"{b:#04x}" for b in buf]))
else:
print(buf.hex())