简体   繁体   English

C#套接字MemoryStream

[英]C# Sockets MemoryStream

So I'm trying to call a method which converts a integer into 4 bytes, 所以我试图调用一个将整数转换为4个字节的方法,

The conversion is written like this - 转换是这样写的 -

    public void put4(int var1)
    {
        this.payload[++this.offset - 1] = (byte)(var1 >> 24);
        this.payload[++this.offset - 1] = (byte)(var1 >> 16);
        this.payload[++this.offset - 1] = (byte)(var1 >> 8);
        this.payload[++this.offset - 1] = (byte)var1;
    }

Which puts 哪个放

var1

into 4 bytes 分为4个字节

but how could I use this with memorystream? 但是我该如何与memorystream一起使用呢?

I know I can send a singlebyte with 我知道我可以用

  MemoryStream ms = new MemoryStream();

  ms.WriteByte(1);

but I want to send "1" in 4 bytes 但我想以4个字节发送“ 1”

what I have tried is, 我尝试过的是

 ms.WriteByte.put4(1);

I'm very confused to be honest with you, as I'm not familiar with networking or bytes, but what I do know is, that this specific integer needs to be sent in 4 bytes not as a single byte. 我很难对你说实话,因为我不熟悉网络或字节,但我所知道的是,这个特定的整数需要以4个字节发送而不是单个字节。

There are several ways you could do this, ie you could use the BinaryWriter class 有几种方法可以执行此操作,即可以使用BinaryWriter

However, to answer your question in regards to a MemoryStream 但是,要回答有关MemoryStream

BitConvert.GetBytes(Int32) BitConvert.GetBytes(Int32)已

Returns the specified 32-bit signed integer value as an array of bytes. 以字节数组的形式返回指定的32位有符号整数值。

var bytes = BitConvert.GetBytes(someInt);

stream.Write(bytes,0,bytes.Length);

Note : You have to be-careful about the platform you are using, and the endianness 注意 :您必须小心使用的平台和字节序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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