'How to read files as hex

I want to to be able to be given an input file with any sort of extension and read it in as hex or binary, but in a string or something. Not like open(file_path, 'rb') in python. Preferably in python or JS.



Solution 1:[1]

Can use print() with "x" format to format a byte as 2-digit hex string. Use 'rb' file mode to open file in binary mode to process file stream as a sequence of bytes. You can read a block of data at a time then iterate over each block one byte at a time.

import sys

with open(sys.argv[1], 'rb') as fin:
    while True:
        data = fin.read(16)
        if len(data) == 0:
            break
        # iterate over each byte in byte sequence
        for b in data:
            print(' {:02x}'.format(b), end='')
        print()

If run code above on the source code then output would be a sequence of 16 hex numbers on each line.

Output:

69 6d 70 6f 72 74 20 73 79 73 0d 0a 0d 0a 77 69
74 68 20 6f 70 65 6e 28 73 79 73 2e 61 72 67 76
...
3d 27 27 29 0d 0a 20 20 20 20 20 20 20 20 70 72
69 6e 74 28 29 0d 0a

For example, the first line "import sys" is output as 69 6d 70 6f 72 74 20 73 79 73 followed by 0d 0a for CR LF characters.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1