[英]Converting C# to Python base64 encoding
I am trying to convert a function from C# to python.我正在尝试将函数从 C# 转换为 python。
My C# code:我的 C# 代码:
static string Base64Encode(string plainText)
{
char[] arr = plainText.ToCharArray();
List<byte> code16 = new List<byte>();
int i = 1;
string note = "";
foreach (char row in arr)
{
if (i == 1)
{
note += "0x" + row;
}
else if (i == 2)
{
note += row;
code16.Add(Convert.ToByte(note, 16));
note = "";
i = 0;
}
i++;
}
return System.Convert.ToBase64String(code16.ToArray());
}
My Python code:我的 Python 代码:
def Base64Ecode(plainText):
code16 = []
i = 1
note = ''
for row in plainText:
if i == 1:
note += '0x' + row
elif i == 2:
note += row
code16.append(int(note, 16))
note = ''
i = 0
i += 1
test = ''
for blah in code16:
test += chr(blah)
print(base64.b64encode(test.encode()))
Both code16
values are the same but I have an issue when I try to base64
encode the data.两个
code16
值相同,但是当我尝试对数据进行base64
编码时遇到问题。 C# takes a byte array but pyton takes a string and I am getting two different results. C# 需要一个字节数组,但 pyton 需要一个字符串,我得到两个不同的结果。
string.encode()
uses the utf-8 encoding by default, which probably creates some multi-byte chars you don't want. string.encode()
默认使用 utf-8 编码,这可能会创建一些您不想要的多字节字符。
Use string.encode("latin1")
to create bytes from 00
to FF
.使用
string.encode("latin1")
创建从00
到FF
字节。
That said, there is an easier method in python to convert a Hex-String to a bytearray (or bytes object):也就是说,python 中有一种更简单的方法可以将十六进制字符串转换为字节数组(或字节对象):
base64.b64encode(bytes.fromhex(plainText))
gives the same result as your function.给出与您的函数相同的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.