LoginSignup
0
0

pythonでhex読み込み

Posted at

Pythonで16進エディタを作りたかったのですが、まずはバイナリデータを表示するところまでです

def print_hex(filename, length=256):
    """ 指定されたファイルの最初の 'length' バイトをヘックス形式で表示 """
    with open(filename, 'rb') as file:
        data = file.read(length)
        hex_data = data.hex()  # バイナリデータを16進数の文字列に変換
        formatted_hex = ""
        for j in range(0, len(hex_data), 32):  # 16バイト(32文字)ごとに処理
            line = ""
            for i in range(j, min(j + 32, len(hex_data)), 2):  # 各バイト(2文字)ごとに処理
                byte_hex = hex_data[i:i+2]
                line += byte_hex + " "
            formatted_hex += line.strip() + "\n"  # 末尾の空白を削除し、改行を追加
        print(formatted_hex)

print_hex('test.txt')
0
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0