python字符串转二进制代码_Python向文件写入二进制代码,字符串转换等

Python平台:Python 2.7(经测试,Python3.6.1可用,需要添加少许改动,详见文章末尾)

二进制代码查看工具:WinHex

假设我们有如下16进制代码,需要当成binary文件写入:

output_code = """00400000,24090002

00400004,21280004

00400008,00082021

0040000c,24020001

00400010,0000000c"""

那么只需要使用bytearray.fromhex方法,它会直接将8位16进制的字符串转换成相应binary:

file1 = open('byte_file', 'wb')

output_code = output_code.split('\n')

for line in output_code:

print line

file1.write(bytearray.fromhex(line.split(',')[0]))

file1.write(bytearray.fromhex(line.split(',')[1]))

file1.close()

假设我们遇到的是2进制字符串咋办呢?下面是一个32位的字符串:

binary_str = "10001100000000100000000000000100"

# ----------> 123456789 123456789 123456789 12一共32位2进制数字

下面的代码能把32位的2进制str,转换成8位的16进制str(2^32 == 16^8):

def transfer_32binary_code(opcode_in):

optcode_str = ''

for i in range(len(opcode_in) / 4):

small_xe = opcode_in[4 * i: 4 * (i + 1)]

small_xe = hex(int(small_xe, 2))

optcode_str += small_xe[2]

return optcode_str

输出结果如下:

8c020004

我们将前面的步骤结合起来,写入一个binary文件,内容为8c020004,试一试:

file1 = open('hex_16_str.binary', 'wb')

hex_16_str = transfer_32binary_code('10001100000000100000000000000100')

print hex_16_str

file1.write(bytearray.fromhex(hex_16_str))

file1.close()

我们通过WinHex打开保存的binary文件,确认写入的二进制代码符合

f8d7f2022cea90f0ec3d2ccfbdcdc482b8c.jpg

附录:

Python3.6.1使用以上功能的时候,需要注意len除以int后是float的问题,float不能被range函数接收,需要改动如下:

def transfer_32binary_code(opcode_in):

optcode_str = ''

for i in range(int(len(opcode_in) / 4)): # in python 3.6.1, int divide by int is float

small_xe = opcode_in[4 * i: 4 * (i + 1)]

small_xe = hex(int(small_xe, 2))

optcode_str += small_xe[2]

return optcode_str

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值