简体   繁体   中英

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.

Edit: @JasonM1 's answer worked for me. Turns out I was unaware of how to use open() properly. Feel free to down vote.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM