I am trying to upload a base64 of a signature but I need it to be a base64 encoding of an array of 16-bit words stored in little-endian byte order. Can anyone help me convert the base64 to 16-bit array in little-endian byte and then convert it again to base64?
To do this you can create arrays of the correct type (byte[] and short[]) and use Buffer.BlockCopy()
to copy the bytes between them, thus converting the data.
This does not account for little-endian/big-endian differences, but since you state that this only needs to run on little-endian systems, we don't need to worry about it.
Here's a sample console app that demonstrates how to do the conversion. It does the following:
Here's the code:
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");
}
}
}