Brian Kramer

I have C# code that creates an sbyte[ ] and J# code that consumes it. I can't use byte[ ] because Java doesn't support unsigned bytes (lame oversight on Sun's part).

So my problem is this. BinaryWriter has an overload that takes byte[ ], but not sbyte[ ]. Is there a more efficient way to do the following

Code Snippet

private static void WriteFile(string outputFile, sbyte[] bytes)

{

FileStream outputStream = new FileStream(outputFile, FileMode.Create);

BinaryWriter binaryWriter = new BinaryWriter(outputStream);

foreach(sbyte element in bytes )

{

binaryWriter.Write(element);

}

binaryWriter.Close();

}

Note that this code is on the producer/C# side. (The bytes go to the J# code as well as to a file.)

Thanks,

Brian



Re: Visual C# Language Calling BinaryWriter on sbyte[]

Peter Ritchie

Although C# doesn't allow a direct cast from sbyte[] to byte[] (and vice versa), IL does. You can get around that by first casting your sbyte array to Array. For example:

Code Snippet

sbyte[] sbytes = new sbyte[] {1,2,3,4,5};

using(FileStream outputStream = new FileStream("file.dat", FileMode.Create))
{
using(BinaryWriter binaryWriter = new BinaryWriter(outputStream))
{
binaryWriter.Write((byte[])(Array)sbytes);
}
}

I don't know for sure if doing it that way is more efficient in the general case than a single write per byte; but I suspect it is.






Re: Visual C# Language Calling BinaryWriter on sbyte[]

Brian Kramer

I knew you'd come to my rescue, Peter. This is a cool trick. It's in place now.


Thanks!


Brian