C# 等效于 Java 中的 ByteArrayOutputStream
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22062521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# equivalent for ByteArrayOutputStream in java
提问by Vaibhav
I have java
code as
我有java
代码
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(tokenBytes);
baos.write(signedData);
byte[] finalout = baos.toByteArray();
where tokenBytes and signedData are byte arrays.In c#
I have written as
其中 tokenBytes 和 signedData 是字节数组。在c#
我写为
using (MemoryStream stream = new MemoryStream())
{
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Write(tokenBytes);
writer.Write(signature);
}
finalBytesToSend = stream.ToArray();
}
where tokenBytes , signature and finaleBytesToSend are byte arrays.
其中 tokenBytes 、 signature 和 finaleBytesToSend 是字节数组。
Is it correct? OR is there any other way to do it?
这是正确的吗?或者有其他方法可以做到吗?
回答by Alex Suo
Presumably I assume you are writing a Java-C# serialization scheme. I think there are 3 things you might want to be careful:
据推测,我假设您正在编写 Java-C# 序列化方案。我认为您可能需要注意 3 件事:
- That Java byte array output might contain special deliminator at the end.
- That Java by default using Big-Endian encoding if your data in the byte array wasn't originally just bytes; while C# default is Little Endian encoding.
- That for strings Java is using UTF-16 (Big Endian) and C# UTF-16 by default is Little Endian.
- 该 Java 字节数组输出可能在末尾包含特殊分隔符。
- 如果字节数组中的数据最初不只是字节,那么 Java 默认使用 Big-Endian 编码;而 C# 默认是 Little Endian 编码。
- 对于字符串,Java 使用 UTF-16(Big Endian),C# UTF-16 默认使用 Little Endian。
In my opinion if you are transferring data between Java and C#, you'd better use simply ByteBuffer in Java side and MemoryStream/BinaryReader/BinaryWrite in C# side. Setting UTF-16 Big Endian correctly in C# side, and write your own de-serializer for stuff like int/long/double primitives. That makes it work.
在我看来,如果您在 Java 和 C# 之间传输数据,最好在 Java 端使用 ByteBuffer,在 C# 端使用 MemoryStream/BinaryReader/BinaryWrite。在 C# 端正确设置 UTF-16 Big Endian,并为 int/long/double 基元等内容编写自己的反序列化器。这使它起作用。