Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert sbyte[] to base64 string?

How can I convert sbyte[] to base64 string?

I cannot convert that sbyte[] to a byte[], to keep interoperability with java.

like image 308
marcelo-ferraz Avatar asked Sep 05 '11 19:09

marcelo-ferraz


2 Answers

You absolutely can convert the sbyte[] to a byte[] - I can pretty much guarantee you that the Java code will really be treating the byte array as unsigned. (Or to put it another way: base64 is only defined in terms of unsigned bytes...)

Just convert to byte[] and call Convert.ToBase64String. Converting to byte[] is actually really easy - although C# itself doesn't provide a conversion between the two, the CLR is quite happy to perform a reference conversion, so you just need to fool the C# compiler:

sbyte[] x = { -1, 1 };
byte[] y = (byte[]) (object) x;
Console.WriteLine(Convert.ToBase64String(y));

If you want to have a genuine byte[] you can copy:

byte[] y = new byte[x.Length];
Buffer.BlockCopy(x, 0, y, 0, y.Length);

but personally I'd stick with the first form.

like image 76
Jon Skeet Avatar answered Oct 13 '22 23:10

Jon Skeet


class Program
{
    static void Main()
    {
        sbyte[] signedByteArray = { -2, -1, 0, 1, 2 };
        byte[] unsignedByteArray = (byte[])(Array)signedByteArray; 
        Console.WriteLine(Convert.ToBase64String(unsignedByteArray));
    }
}
like image 44
Darin Dimitrov Avatar answered Oct 14 '22 00:10

Darin Dimitrov