Search code examples
c#socketsbytememorystream

C# Sockets MemoryStream


So I'm trying to call a method which converts a integer into 4 bytes,

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

but how could I use this with 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

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.


Solution

  • There are several ways you could do this, i.e you could use the BinaryWriter class

    However, to answer your question in regards to a MemoryStream

    BitConvert.GetBytes(Int32)

    Returns the specified 32-bit signed integer value as an array of bytes.

    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