簡體   English   中英

C# 將 base64 字符串轉換為以 little-endian 字節順序存儲的 16 位字

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

我正在嘗試上傳簽名的 base64 但我需要它是 base64 編碼的 16 位字數組以小端字節順序存儲。 誰能幫我將 base64 轉換為 little-endian 字節的 16 位數組,然后再將其轉換為 base64?

為此,您可以創建正確類型(byte[] 和 short[])的 arrays 並使用Buffer.BlockCopy()在它們之間復制字節,從而轉換數據。

這並沒有考慮 little-endian/big-endian 的差異,但是由於您 state 認為這只需要在 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");
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM