簡體   English   中英

在python中將字節字符串轉換為十六進制

[英]Converting string of bytes to Hex in python

鑒於此文件(utf8):

00000000  30 31 3a 32 35 20 e2 87  92 20 31 32 2f 32 34 2f  |01:25 ... 12/24/|
00000010  32 30 31 39 20 e2 87 89  30 31 3a 33 31 20 44 49  |2019 ...01:31 DI|
00000020  53 4b 20 46 20 e2 99 a3  20 0d 0a                 |SK F ... ..|

我的意圖是獲取一個文件或字節字符串,並將其轉換為十六進制表示。 我創建了以下代碼:

def c2h(data):
    def c2h(c):
        hb = hex(ord(c)).replace('0x','')
        return hb if len(hb) == 2 else ''.join('0'+hb)
    strbuf = []
    i = 0
    for c in data:
        if ord(c) > 255:
        raise ValueError("ord value of char @ position:{:2d} is > 255".format(i))
        strbuf.append(c2h(c))
        i += 1
    return ''.join(strbuf)

然后我把上面的代碼在 Mac、Windows 和 Linux 上運行。 這是結果。

Mac:Python 2.7.16

>>> file = '/Volumes/TEMP/KDACCT.TXT'
>>> f = open(file, 'r')
>>> s1 = f.read().rstrip('\r\n')
>>> s1
'01:25 \xe2\x87\x92 12/24/2019 \xe2\x87\x8901:31 DISK F \xe2\x99\xa3 '
>>> c2h(s1)
'30313a323520e287922031322f32342f3230313920e2878930313a3331204449534b204620e299a320'

我得到了我所期望的,但是如果我在 Windows 或 Linux 中使用相同的文件,我會得到一個 ValueError。

這是 Windows 交互:Windows: Python 3.6.8

>>> file = 'c:\\temp\\kdacct.txt'
>>> f = open(file, 'r')
>>> s1 = f.read().rstrip('\r\n')
>>> s1
'01:25 ⇒ 12/24/2019 ⇉01:31 DISK F ♣ '
>>> c2h(s1)
I get ValueError: ord value of char @ position:10 is > 255

請注意,Windows 存儲 BOM。

這是 Linux 交互:Linux: Python 3.6.8

>>> file = '/media/sf_Linux_SHR/KDACCT.TXT'
>>> f = open(file, 'r')
>>> s1 = f.read().rstrip('\r\n')
>>> s1
'01:25 ⇒ 12/24/2019 ⇉01:31 DISK F ♣ '
>>> c2h(s1)
I get ValueError: ord value of char @ position: 6 is > 255

我的問題是如何在 Windows/Linux 中獲得與在 Mac 上相同的結果。 我認為這與編碼有關,我只是不知道需要發生什么。

這里有幾個問題在起作用

  1. 您正在將二進制文件作為 ascii 文件讀取。 您應該使用rb而不是r作為open()參數
  2. 您正在混合 Python 2 和 Python 3,在這種情況下,它們的行為有點不同。

這是一個適用於兩者的版本:

from __future__ import print_function


with open('/Volumes/TEMP/KDACCT.TXT', 'rb') as fh:
    characters = bytearray(fh.read())
    for character in characters:
        print('%02x' % character, end='')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM