Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# equivalent for ByteArrayOutputStream in java

I have java code as

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

 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.

Is it correct? OR is there any other way to do it?

like image 694
Vaibhav Avatar asked Feb 27 '14 08:02

Vaibhav


1 Answers

Presumably I assume you are writing a Java-C# serialization scheme. I think there are 3 things you might want to be careful:

  1. That Java byte array output might contain special deliminator at the end.
  2. 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.
  3. That for strings Java is using UTF-16 (Big Endian) and C# UTF-16 by default is 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.

like image 58
Alex Suo Avatar answered Oct 20 '22 11:10

Alex Suo