2017-01-11 116 views
-2

我使用python3.5,我希望寫輸出我在十六進制字節得到(b'\x00'b'\x01'等),以Python字符串與\x00 -> 0\x01 -> 1,我也有這種感覺,可以很容易地,並在完成非常pythonic的方式,但半小時的谷歌搜索仍然讓我覺得最簡單的就是用手繪製一本字典(我實際上只需要它從0到7)。蟒蛇十六進制二進制轉換爲字符串

Input Intended output 
b'\x00' 0 or '0' 
b'\x01' 1 or '1' 

+1

什麼是你的輸入,什麼是想要的輸出? – Daniel

+1

'b'表示'字節',而不是二進制。 '\ x00'不是字符串'0',但是代碼爲'0'的字符不能顯示,所以Python會顯示它的代碼。 – furas

+0

你用'b「\ x0F」' - '「F」'或'「15」'指望的結果是什麼? – furas

回答

2

不知道,如果你想這樣的結果,但嘗試

output = [str(ord(x)) for x in output] 
+0

不錯,但會出現'\ x0F'和類似的問題;) – furas

+1

好吧......他說「我只是真的需要它從0到7」:) –

+0

好點 - 我錯過了這部分:) – furas

0

如果wiil需要b"\x0F"轉換成F然後使用

print(hex(ord(b'\x0F'))[2:]) 

或與format()

print(format(ord(b'\x0F'), 'X')) # '02X' gives string '0F' 
print('{:X}'.format(ord(b'\x0F'))) # '{:02X}' gives string '0F' 
1

一個字節字符串自動是一個數字列表。

input_bytes = b"\x00\x01" 
output_numbers = list(input_bytes) 
1

你只是想找這樣的事情嗎?

for x in range(0,8): 
    (x).to_bytes(1, byteorder='big') 

輸出是:

b'\x00' 
b'\x01' 
b'\x02' 
b'\x03' 
b'\x04' 
b'\x05' 
b'\x06' 
b'\x07' 

或者相反:

byteslist = [b'\x00', 
b'\x01', 
b'\x02', 
b'\x03', 
b'\x04', 
b'\x05', 
b'\x06', 
b'\x07'] 

for x in byteslist: 
    int.from_bytes(x,byteorder='big') 

輸出:

0 
1 
2 
3 
4 
5 
6 
7 
相關問題