Kenny
Kenny

Reputation: 1142

Convert short to int

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
            }
        }


    }
}

Upvotes: 2

Views: 26739

Answers (4)

Philippe Par&#233;
Philippe Par&#233;

Reputation: 4418

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;

Upvotes: 4

Guffa
Guffa

Reputation: 700362

To get the short from those two bytes in the data you can use the BitConverter.GetInt16 method.

As converting from short to int is a widening conversion, you don't even have to specify it, just put the short value in an int variable and it's implicitly converted:

int payloadSize = BitConverter.GetInt16(data, 2);

Upvotes: 1

Mihai Caracostea
Mihai Caracostea

Reputation: 8466

Why not just

int myInt = (int)BitConverter.ToInt16(data, 2);

?

Upvotes: 3

Zarwan
Zarwan

Reputation: 5787

Your problem is that you're trying to cast a short[] to an int. You can cast an individual short to an int by doing (int)myShort, but you can't do that with an array. You have to cast each index individually.

short[] myShorts = new short[2];
int[] myInts = new int[myShorts.Length];

for (int i = 0; i < myShorts.Length; i++) {
    myInts[i] = (int)myShorts[i];
}

Upvotes: 1

Related Questions