不同进制转换,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))
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值