Reputation: 23690
I'm trying to send the Length
of a Byte array to my server, so that it knows how much data to read.
I get the length of the Byte[] message
array using int messageLength = message.Length
How do I represent this integer messageLength
a four-byte integer?
Upvotes: 1
Views: 1583
Reputation: 21337
You can use
int length = message.Length;
BitConvert.GetBytes(length);
http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx
Upvotes: 1
Reputation: 33738
A byte in C# is 8 bits.. 8 bits * 4 bytes = 32 bits.. so you want to use a System.Int32.
Upvotes: 0
Reputation: 9060
message[0] = length & 0xFF;
message[1] = (length >> 8) & 0xFF;
message[2] = (length >> 16) & 0xFF;
message[3] = (length >> 24) & 0xFF;
To recover it...
int length = message[0] | (message[1] << 8) | (message[2] << 16) | (message[3] << 24);
Upvotes: 0