Luke
Luke

Reputation: 23690

C# How to represent an Int as four-byte integer

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

Answers (5)

L.B
L.B

Reputation: 116148

Use BitConvertor BitConverter.GetBytes(message.Length);

Upvotes: 6

meziantou
meziantou

Reputation: 21337

You can use

int length = message.Length;
BitConvert.GetBytes(length);

http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx

Upvotes: 1

Sam Axe
Sam Axe

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

Felice Pollano
Felice Pollano

Reputation: 33252

Use the BitConverter.GetBytes(int32) class

Upvotes: 5

Salvatore Previti
Salvatore Previti

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

Related Questions