如何将sbyte []转换为base64字符串?

时间:2011-09-05 19:47:42

标签: c# .net string bytearray base64

如何将sbyte[]转换为base64字符串?

我无法将sbyte[]转换为byte[],以保持与java的互操作性。

2 个答案:

答案 0 :(得分:12)

你绝对可以sbyte[]转换为byte[] - 我几乎可以保证Java代码真的正在处理字节数组为无符号。 (换句话说:base64只是定义的无符号字节...)

转换为byte[]并致电Convert.ToBase64String。转换为byte[]实际上非常简单 - 虽然C#本身不提供两者之间的转换,但CLR很乐意执行引用转换,因此您只需要欺骗C#编译器:

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

如果您想要正版 byte[],可以复制:

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

但我个人坚持使用第一种形式。

答案 1 :(得分:5)

class Program
{
    static void Main()
    {
        sbyte[] signedByteArray = { -2, -1, 0, 1, 2 };
        byte[] unsignedByteArray = (byte[])(Array)signedByteArray; 
        Console.WriteLine(Convert.ToBase64String(unsignedByteArray));
    }
}