I feel like I’m taking 2 steps back with this question, but something is confusing me a little. I’m working with some communication via TCP/IP and byte[]’s.
So I start building my byte[] array, and the third byte requires the length of the byte[]. If I declare my byte like so;
byte[] bytesToSend = new byte[119];
and then fill in the first three bytes with data..
bytesToSend[0] = 0x40;
bytesToSend[1] = 0x40;
bytesToSend[2] = Encoding.ASCII.GetBytes(bytesToSend.Length.ToString())[0];
and finally just print out the third byte, which should contain the length;
MessageBox.Show(BitConverter.ToString(bytesToSend));
should I be expecting it to return the byte size of 119, or is this just the maximum size? Currently it’s returning hex “0x31”, which as far as i’m aware doesn’t equal 119 or 3. This is no doubt something simple / fundamental I’m missing, but could someone point me in the right direction?
Seems you are unclear on what you are actually doing here:
Let’s break this line down:
Returns the integer 119
Returns the string “119”
Returns a byte array of the characters that make up the ascii string “119”.
Get just the first byte of this array, which would equal 0x31, because this is the ascii code for the character ‘1’.
Also, there is no such thing as an actual size of a c#
Array. There is only aLength. If you mean to ask how many of the elements contain non-zero bytes, that’s another story, but once you declareYou get a byte array with 119 elements, and it’s
Lengthwill always be 119, regardless of how many elements you have modified.If you need to use a collection with a more dynamic size, consider using a
List<byte>instead.