
Problem with the length of byte arrays and the length (in bytes) of diffrent datatypes
Hi!
At the moment I am working on a application that sends and recives
arrays of bytes. And in doing so I have encountered a few things that
make me a bit confused...
----- THE SAMPLE CODE -------
Dim ByteArray(7) As Byte
Dim intValue As Int32 = 12
Console.Write(Encoding.ASCII.GetByteCount(intValue) & vbNewLine)
ByteArray = BitConverter.GetBytes(intValue)
Console.Write(ByteArray.Length & vbNewLine)
Console.Write(ByteArray(5))
-------- THE OUPUT ----------
2
4
An unhandled exception of type 'System.IndexOutOfRangeException'
occurred in abc.exe
Additional information: Index was outside the bounds of the array.
------ THE QUESTIONS --------
1. I have figured out that "Encoding.ASCII.GetBytes" gives me the
chars (2 bytes) while "BitConverter.GetBytes" gives me the acctual
integer (4 bytes). And I know now that
"Encoding.ASCII.GetByteCount(intValue)" gives me the number of chars
(2), but what if I want to count the bytes of "intValue" when treated
as a Int32? I want it to return a 4...
2. How come that after I have put a 4 byte value into the array the
length property gives me 4 bytes/pos and not 8 as it was declared? And
why can't I read or write to, for example byte 7!?!
3. If I want to read and write random bytes in my array, must I then
first fill the array with dummy values?
-----------------------------
Regards,
/Jonas