[英]How can I convert sbyte[] to base64 string?
How can I convert sbyte[]
to base64 string? 如何将
sbyte[]
转换为base64字符串?
I cannot convert that sbyte[]
to a byte[]
, to keep interoperability with java. 我无法将
sbyte[]
转换为byte[]
,以保持与java的互操作性。
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. 你绝对可以将
sbyte[]
转换为byte[]
- 我几乎可以保证Java代码真的将字节数组视为无符号。 (Or to put it another way: base64 is only defined in terms of unsigned bytes...) (或者换句话说:base64只根据无符号字节定义 ......)
Just convert to byte[]
and call Convert.ToBase64String
. 只需转换为
byte[]
并调用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: 转换为
byte[]
实际上非常简单 - 虽然C#本身不提供两者之间的转换,但CLR非常乐意执行引用转换,因此您只需要欺骗C#编译器:
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[]
你可以复制:
byte[] y = new byte[x.Length];
Buffer.BlockCopy(x, 0, y, 0, y.Length);
but personally I'd stick with the first form. 但就个人而言,我坚持使用第一种形式。
class Program
{
static void Main()
{
sbyte[] signedByteArray = { -2, -1, 0, 1, 2 };
byte[] unsignedByteArray = (byte[])(Array)signedByteArray;
Console.WriteLine(Convert.ToBase64String(unsignedByteArray));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.