【问题标题】:Converting C# to Python base64 encoding将 C# 转换为 Python base64 编码
【发布时间】:2020-08-24 16:07:49
【问题描述】:

我正在尝试将一个函数从 C# 转换为 python。

我的 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());
}

我的 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()))

code16 的两个值相同,但是当我尝试对数据进行 base64 编码时遇到问题。 C# 需要一个字节数组,但 pyton 需要一个字符串,我得到两个不同的结果。

【问题讨论】:

  • 你试过调试这个吗?字符串/字符的编码可能不同
  • 两个数组似乎相同(code16),但我坚持将数组转换为一个值以传递给 python 中的 b64encode

标签: python c# arrays base64


【解决方案1】:

string.encode() 默认使用 utf-8 编码,这可能会创建一些您不想要的多字节字符。

使用string.encode("latin1") 创建从00FF 的字节。

也就是说,python 中有一种更简单的方法可以将十六进制字符串转换为字节数组(或字节对象):

base64.b64encode(bytes.fromhex(plainText))

给出与您的函数相同的结果。

【讨论】:

    猜你喜欢
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 2020-07-25
    • 2011-11-20
    • 2015-05-30
    • 1970-01-01
    • 2011-04-27
    相关资源
    最近更新 更多