python一行代码实现二进制与字符串的相互转化

方法一(纯代码):

# 二进制转字符串
二进制中间有空格:

data= '01101000 01100101 01101100 01101100 01101111'  # 二进制字符串
result = ''.join(chr(int(i, 2)) for i in data.split())  # 转换为字符串
print(result)

二进制中间无空格:

data = '0110011001100001011010110110010101011111011001100110110001100001011001110111101101101100011101010110101101110011010111110110110001101001011010110110010101011111011110010110111101110101010111110110001001110010011011110110101101100101010111110110110101111001010111110110101101100101011110010010111001111101'
res = ''.join(chr(int(data[i:i+8],2)) for i in range(0,len(data),8))
print(res)

# 字符串转二进制

string = 'hello' 
result = ' '.join(format(ord(char), '08b') for char in string)  
print(result) 

使用 format() 将 ASCII 码值格式化为8位的二进制数,其中 ‘08b’ 表示使用8位二进制进行表示

方法二(库)

import binascii
# 二进制转为字符串

data = '0110011001100001011010110110010101011111011001100110110001100001011001110111101101101100011101010110101101110011010111110110110001101001011010110110010101011111011110010110111101110101010111110110001001110010011011110110101101100101010111110110110101111001010111110110101101100101011110010010111001111101'
res = binascii.unhexlify('%x' % int(data,2)).decode()[2:] 
print(res)

# 字符串转化为二进制
str = 'fake_flag{luks_like_you_broke_my_key.}'
res = bin(int(binascii.hexlify(str.encode()).decode(),16))
print(res) # 把前缀0b去掉

你可能感兴趣的:(python,python,密码学,安全)