简体   繁体   中英

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?

使用BitConvertor BitConverter.GetBytes(message.Length);

You can use

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

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

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);

C#中的一个字节是8位。8位* 4字节= 32位..因此,您想使用System.Int32。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM