C# 将 base64 字符串转换为以 little-endian 字节顺序存储的 16 位字

C# Converting base64 string to 16-bit words stored in little-endian byte order

我正在尝试上传签名的 base64,但我需要它是以 little-endian 字节顺序存储的 16 位字数组的 ba​​se64 编码。谁能帮我将 base64 转换为 little-endian 字节的 16 位数组,然后再将其转换为 base64?

为此,您可以创建正确类型的数组(byte[] 和 short[])并使用 Buffer.BlockCopy() 在它们之间复制字节,从而转换数据。

这没有说明 little-endian/big-endian 差异,但由于您声明这只需要 运行 在 little-endian 系统上,我们不必担心。

这是一个示例控制台应用程序,演示了如何进行转换。它执行以下操作:

  1. 创建一个包含 0..99 的短裤数组。
  2. 将短裤数组转换为字节数组(保留字节顺序)。
  3. 将字节数组转换为 base 64 字符串。
  4. 将 base 64 字符串转换回字节数组。
  5. 将字节数组转换回短整型数组(保留字节顺序)。
  6. 将转换后的短裤数组与原始数组进行比较以证明正确性。

代码如下:

using System;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create demo array of shorts 0..99 inclusive.

            short[] sourceShorts = Enumerable.Range(0, 100).Select(i => (short)i).ToArray();

            // Convert array of shorts to array of bytes. (Will be little-endian on Intel.)

            int byteCount = sizeof(short) * sourceShorts.Length;
            byte[] dataAsByteArray = new byte[byteCount];
            Buffer.BlockCopy(sourceShorts, 0, dataAsByteArray, 0, byteCount);

            // Convert array of bytes to base 64 string.

            var asBase64 = Convert.ToBase64String(dataAsByteArray);
            Console.WriteLine(asBase64);

            // Convert base 64 string back to array of bytes.

            byte[] fromBase64 = Convert.FromBase64String(asBase64);

            // Convert array of bytes back to array of shorts.

            if (fromBase64.Length % sizeof(short) != 0)
                throw new InvalidOperationException("Byte array size must be multiple of sizeof(short) to be convertable to shorts");

            short[] destShorts = new short[fromBase64.Length/sizeof(short)];
            Buffer.BlockCopy(fromBase64, 0, destShorts, 0, fromBase64.Length);

            // Prove that the unconverted shorts match the source shorts.

            if (destShorts.SequenceEqual(sourceShorts))
                Console.WriteLine("Converted and unconverted successfully");
            else
                Console.WriteLine("Error: conversion was unsuccessful");
        }
    }
}