在C#转换2个字节为短 [英] Converting 2 bytes to Short in C#

查看:648
本文介绍了在C#转换2个字节为短的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想2个字节转换成一个无符号的短,所以我可以检索实际的服务器端口值。我是从这个协议规范下回复格式立足其关闭。我试着用BitConverter.ToUint16()这一点,但问题是,它似乎不扔的预期值。请参阅下面的示例实现:

I'm trying to convert 2 bytes into an unsigned short so I can retrieve the actual server port value. I'm basing it off from this protocol specification under Reply Format. I tried using BitConverter.ToUint16() for this, but the problem is, it doesn't seem to throw the expected value. See below for a sample implementation:

        int bytesRead = 0;

        while(bytesRead < ms.Length)
        {
            int first = ms.ReadByte() & 0xFF;
            int second = ms.ReadByte() & 0xFF;
            int third = ms.ReadByte() & 0xFF;
            int fourth = ms.ReadByte() & 0xFF;
            int port1 = ms.ReadByte();
            int port2 = ms.ReadByte();
            int actualPort = BitConverter.ToUInt16(new byte[2] {(byte)port1 , (byte)port2 }, 0);
            string ip = String.Format("{0}.{1}.{2}.{3}:{4}-{5} = {6}", first, second, third, fourth, port1, port2, actualPort);
            Debug.WriteLine(ip);
            bytesRead += 6;
        }

给定一个样本数据,假设两个字节值,我有105安培; 135,转换后的预期端口值应该是27015,而是我得到使用BitConverter一个的34665值。

Given one sample data, lets say for the two byte values, I have 105 & 135, the expected port value after conversion should be 27015, but instead I get a value of 34665 using BitConverter.

我这样做了错误的方式?任何帮助将是非常美联社preciated。谢谢!

Am I doing it the wrong way? Any help would be much appreciated. Thanks!

推荐答案

如果你扭转BitConverter调用的值,你应该得到预期的结果:

If you reverse the values in the BitConverter call, you should get the expected result:

int actualPort = BitConverter.ToUInt16(new byte[2] {(byte)port2 , (byte)port1 }, 0);

在一个小端架构,低位字节需要是第二个数组中为止。而作为lasseespeholt在评论中指出的那样,你需要逆转大端架构的顺序。这可能与<一检查href=\"http://msdn.microsoft.com/en-us/library/system.bitconverter.islittleendian.aspx\">BitConverter.IsLittleEndian属性。或者,它可能是一个更好的解决方案的整体使用<一个href=\"http://msdn.microsoft.com/en-us/library/aa329627%28v=VS.71%29.aspx\">IPAddress.HostToNetworkOrder (第一转换值,然后调用该方法把字节按照正确的顺序不管字节序)。

On a little-endian architecture, the low order byte needs to be second in the array. And as lasseespeholt points out in the comments, you would need to reverse the order on a big-endian architecture. That could be checked with the BitConverter.IsLittleEndian property. Or it might be a better solution overall to use IPAddress.HostToNetworkOrder (convert the value first and then call that method to put the bytes in the correct order regardless of the endianness).

这篇关于在C#转换2个字节为短的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆