Writing int as byte using streamwriter in VB.NET

2.7k Views Asked by At

I have a java function, and am trying to mimic the same functionality in VB.NET.

The Java function:

String text = “ABCDEFG”
int length = text.length();
int l1 = length >> 8;
int l2 = length % 256;
swriter.write(new byte[] {(byte)l1, (byte)l2});

My VB.NET Converted function:

Dim text As String = "ABCDEFG"
Dim length As Integer = text.Length
Dim l1 As Integer = length >> 8
Dim l2 As Integer = length Mod 256
Dim tempArr(2) As Byte
tempArr(0) = Convert.ToByte(l1)
tempArr(1) = Convert.ToByte(l2)
swriter.Write(tempArr)

swriter is a StreamWriter

What is is that everytime when I see the values written through streamwriter on the server shows as "System.byte[]". I tried using BitConverter.GetBytes() function also, but it gives the same results.

What is that I am missing? And how to write the numbers as Byte format. In the above example the length of the text is 7("ABCDEFG"), however in my application it will be more than 1000.

1

There are 1 best solutions below

2
On

Take a look at the documentation on the StreamWriter.Write() method. If you browse through those overloads, none of them accepts a byte array. The best match is a string, and so this compiles down to IL that will try to convert your array to a string by calling the array's .ToString() method. Since arrays do not overload the .ToString() method, you get the default implementation of the base Object type, and that just returns the type name... hence your System.byte[] result.

That makes one wonder why a StreamWriter doesn't know what to do with byte arrays. Let's check the documentation on the StreamWriter type, from which I quote:

Implements a TextWriter for writing characters to a stream in a particular encoding.

Aha! The reason there is no byte array overload is that you're using a type specifically designed for working with Text.

To fix this, you need to use a base Stream type or a BinaryWriter type, instead of StreamWriter. Either of those types are perfectly happy to work with byte arrays.

Finally, while I'm at it I need to point out that you declared your array wrong. In VB.Net, the subscript on the array declaration is the index of the last element in the array. Dim tempArr(2) As Byte declares an array with three elements, not two, with indices at 0,1, and 2.