1. 程式人生 > >不同進位制轉換,bytes和str的轉換

不同進位制轉換,bytes和str的轉換

參考網址:
http://www.cnblogs.com/hushaojun/p/7681148.html
https://blog.csdn.net/qq_15727809/article/details/83513074

1,函式說明(幫助文件):
oct() Return the octal representation of an integer.
bin():Return the binary representation of an integer.
ord() :Return the Unicode code point for a one-character string.
chr():Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff
2,例項使用:

# 注意:因為這裡的轉換,中間使用的預設是unicode,如果字元超出unicode的範圍,則會報typeerror錯誤

# 字串到(需要先準換成字元對應的unicode編碼)2進位制
def str_to_bin(s):
    return ' '.join([bin(ord(c)).replace('0b', '') for c in s])

# 字串到 16進位制
# 注意:join 需要的是字串
def str_to_hex(s):
    return ' '.join([hex(ord(c)).replace('0x', '') for c in s])


#  二進位制到字串(現需要把2進位制碼通過int('',2)轉變成對應的unicode碼,然後在通過chr進行轉換)
def bin_to_str(s):
    return ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]])

# 十六進位制到字串
def hex_to_str(s):
    return ''.join([chr(i) for i in [int(b, 16) for b in s.split(' ')]])

3,bytes流和str的轉換
這個轉換和上面的準換還是很不一樣的,注意區分:

# 1,python 3.x 字串和二進位制之間的轉換
# 需要理解一下的就是:在python2.x中,bytes和str在儲存形式上是沒有什麼區別的,但是在3.x後就完全進行了分開。
方法一,utf-8和unicode編碼互轉
data = '你'
binary = data.encode(encoding='utf-8') # 轉換成utf-8字元編碼
result = binary.decode(encoding='utf-8') # 轉換成unicode編碼,python預設Unicode編碼

print(binary)
print(result)

方法二:使用內建函式str和bytes
data = '你好'
bytes_ = bytes(data,encoding='utf-8')
data_ = str(bytes_,encoding='utf-8')

print(data_)
print(bytes_)

方法三:
import binascii  as bs

str_tmp = 'Just Do it!!!'

str_1= b'Just Do it!!!'
str_2 = bytes(str_tmp, encoding='utf-8')
str_3 = str_tmp.encode('utf-8')

# hexlify: Hexadecimal representation of binary data.The return value is a bytes object.
# 用16進位制的形式表示2進位制,返回的結果是bytes流
str2int_1 = int(bs.hexlify(str_1), 16)
# 這個方法和上面的hexlify方法一樣
str2int_2 = int(bs.b2a_hex(str_2), 16)
print (str2int_1)
print (str2int_2)


int2str_1 = bs.unhexlify(hex(str2int_1)[2:])
int2str_2 = bs.a2b_hex(hex(str2int_1)[2:])
print (int2str_1)
print (int2str_2)

a = hex(str2int_1)
print (type(a))