python 字符串 转 bit, bitarray

str 转为 bitarray 很方便使用

from bitarray import bitarray


def str2bitarray(s):
ret = bitarray(''.join([bin(int('1' + hex(c)[2:], 16))[3:] for c in s.encode('utf-8')]))
return ret


def bitarray2str(bit):
return bit.tobytes().decode('utf-8')

def str_to_hex(s):
return ' '.join([hex(ord(c)).replace('0x', '') for c in s])

def hex_to_str(s):
return ''.join([chr(i) for i in [int(b, 16) for b in s.split(' ')]])

def str_to_bin(s):
return ' '.join([bin(ord(c)).replace('0b', '') for c in s])

def bin_to_str(s):
return ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]])

猜你喜欢

转载自www.cnblogs.com/520zm/p/10642057.html