简体   繁体   English

base64解码和字节协商字符串

[英]base64 decode and byte negotiate string

I have base64 encoded string sZCLmg== which is Note . 我有base64编码的字符串sZCLmg== ,这是Note What I am trying to do is to decode it with base64 and then use bytes negotiation to get string Note back. 我正在尝试使用base64对其进行解码,然后使用字节协商来获取字符串Note

import base64
encoded = 'sZCLmg==' #sZCLmg==  Note
data = base64.b64decode(encoded)
print data

mylist = []
mylist.append(data)
#print mylist[0][0]
bytes = mylist[0][0]
print (bytes ^ 0xFF)

but I am getting error: ValueError: invalid literal for int() with base 10: '\\xb1' Any idea please what am I doing wrong to get original string Note ? 但是我收到错误消息:ValueError:以10为基数的int()的无效文字:'\\ xb1'任何想法请问我在做错什么来获取原始字符串Note

In Python2, iterating over the literal '\\xb1\\x90\\x8b\\x9a' produces strings, not bytes. 在Python2中,迭代文字'\\xb1\\x90\\x8b\\x9a'会产生字符串,而不是字节。

One solution would be to use a bytearray . 一种解决方案是使用bytearray

>>> ba = bytearray(data)
>>> ''.join(chr(x ^ 0xFF) for x in ba)
'Note'

As @wovano points out in the comments, also it's possible to do this without using a bytearray, like this: 正如@wovano在注释中指出的那样,也可以不使用字节数组来执行此操作,如下所示:

''.join(chr(ord(x) ^ 0xFF) for x in data) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM