如何在Python中连接和转换十六进制到base 64?

时间:2013-12-27 17:07:52

标签: python hex base64 decimal

我正在尝试将十六进制值转换为base 64。

我有一个脚本可以对每个值进行一些计算 然后我想将最终值转换为base 64。

import base64
for i, v in enumerate([0x31, 0x37, 0x32, 0x2e]):
    z=i+v #adds positional index to hex value
    q=z+0x27 #adds constant 
    x=q^i # XORs with positional index
print (x)

给出:

  

88
  94个
  89个
  91

我正在尝试将这些值转换为base 64。 如果我以这种形式手动输入它们:585e595b,此代码正常工作:

>>> "585e595b".decode('hex').encode('base64')
'WF5ZWw==\n'

4 个答案:

答案 0 :(得分:0)

一种方法:

data = [0x31, 0x37, 0x32, 0x2e]
encoded = base64.b64encode(''.join(hex(x)[2:] for x in data))

答案 1 :(得分:0)

将其用于现有代码...转换为十六进制,然后切断0x并累积在一个变量中。当你完成后,按照你的建议去做。我得到WF5ZWw==输出。

import base64
string = ''
for i, v in enumerate([0x31, 0x37, 0x32, 0x2e]):
    z=i+v #adds positional index to hex value
    q=z+0x27 #adds constant 
    x=q^i # XORs with positional index
    string += hex(x)[2:]
print string.decode('hex').encode('base64')

答案 2 :(得分:0)

我真的不确定你要做什么,但我感觉你正在寻找chr()将一个序数整数转换成它各自的ASCII字符:

values = []

for i, v in enumerate([0x31, 0x37, 0x32, 0x2e]):
    z=i+v #adds positional index to hex value
    q=z+0x27 #adds constant
    x=q^i # XORs with positional index
    values.append(x)

print "585e595b".decode('hex') .encode('base64')

s = ''.join([chr(i) for i in values])
print s.encode('base64')

输出:

WF5ZWw==

WF5ZWw==

答案 3 :(得分:0)

哇,你自己回答了!

您可以从字符串中进行编码或解码转换:

print str(x).encode('base64')    # should be something like this

我还认为您的算法存在问题,因为数字不会叠加到x变量中。 只打印最后一个号码。