简体   繁体   English

将 short 转换为 int

[英]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?我需要将数据包头中的 short 转换为整数,有什么方法可以不影响其值? 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
            }
        }


    }
}

Why not just为什么不只是

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

? ?

Simply do (int)shortValue , you won't lose any information since you convert a 16 bit value to a 32 bit.只需执行(int)shortValue ,您就不会丢失任何信息,因为您将 16 位值转换为 32 位值。

Edit: Also, if you have two shorts and you want to make an int out of it, do this:编辑:另外,如果你有两条短裤并且你想用它制作一个 int,请执行以下操作:

short s0, s1;
int value = s0 << 16 | s1;

Your problem is that you're trying to cast a short[] to an int.您的问题是您试图将 short[] 转换为 int。 You can cast an individual short to an int by doing (int)myShort, but you can't do that with an array.您可以通过执行 (int)myShort 将单个 short 转换为 int,但不能使用数组执行此操作。 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];
}

To get the short from those two bytes in the data you can use the BitConverter.GetInt16 method.要从数据中的这两个字节中获取短路,您可以使用BitConverter.GetInt16方法。

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:由于从short转换为int是一种扩展转换,您甚至不必指定它,只需将short值放在int变量中,它就会被隐式转换:

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

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

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