Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert short to int

Tags:

c#

I need to convert a short from the packet header to an integer, what would be the way without affecting its value? Is there anything else I can do?

private async void ParsePackets(StreamSocket socket)
{
    using (IInputStream input = socket.InputStream)
    {
        byte[] data = new byte[BufferSize];
        IBuffer buffer = data.AsBuffer();
        uint dataRead = BufferSize;

        // Wait for payload size
        while (data.Length < 4)
        {
            await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
            dataRead = buffer.Length;

            short payloadSizeShort = 0;
            // Cannot convert from short to system array
            System.Buffer.BlockCopy(data, 2, payloadSizeShort, 0, 2);

            int payloadSize = (int)payloadSizeShort;

            // Wait for full message
            while (data.Length < (PacketHeaderSize + payloadSize))
            {
                // Block copy
                // Delete message bytes from buffer
                // Break
            }
        }


    }
}
like image 630
Kenny Avatar asked Jan 29 '26 12:01

Kenny


1 Answers

Simply do (int)shortValue, you won't lose any information since you convert a 16 bit value to a 32 bit.

Edit: Also, if you have two shorts and you want to make an int out of it, do this:

short s0, s1;
int value = s0 << 16 | s1;
like image 148
Philippe Paré Avatar answered Feb 01 '26 02:02

Philippe Paré



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!