在 ushort 中编码字节并再次返回

问题描述

我正在尝试在 ushort 中存储两个字节。所以前 8 位是第一个值,最后 8 位是最后一个。我几乎让它工作了,但我在第 20 行出现了这个错误,在那里我移位了:

Severity    Code    Description Project File    Line    Suppression State
Error   CS0266  Cannot implicitly convert type 'int' to 'ushort'. An explicit conversion exists (are you missing a cast?)   Bit Stuff   C:\Users\perqj\DropBox\GM\Bit Stuff\Bit Stuff\Form1.cs  42  Active

代码如下:

        byte val1 = 1;
        byte val2 = 1;

        byte[] val = new byte[2];

        val[0] = val1;
        val[1] = val2;

        ushort asShort = BitConverter.ToUInt16(val,0);

        ushort mask1 = 0x00ff; //0b_0000_0000_1111_1111    Haven't tried,yet
        ushort mask2 = 0xff00; //0b_1111_1111_0000_0000    Haven't tried,yet

        ushort short1 = asShort;
        ushort short2 = asShort;
        ushort byteShift = 8;

        short1 &= mask1;
        short2 &= mask2;

        short2 = short2 >> byteShift;

        string binaryMask1 = Convert.ToString(mask1,2);
        string binaryMask2 = Convert.ToString(mask2,2);
        string binaryShort1 = Convert.ToString(short1,2);
        string binaryShort2 = Convert.ToString(short2,2);

        listBox1.Items.Add("val1: " + val1);
        listBox1.Items.Add("val2: " + val2);
        listBox1.Items.Add("Short: " + asShort);
        listBox1.Items.Add("mask1: " + mask1 + "  " + binaryMask1);
        listBox1.Items.Add("mask2: " + mask2 + "  " + binaryMask2);
        listBox1.Items.Add("val1: " + short1 + "  " + binaryShort1);
        listBox1.Items.Add("val2: " + short2 + "  " + binaryShort2);

解决方法

我通常使用这样的代码:

    class Program
    {
        static void Main(string[] args)
        {
            byte[] input = new byte[] { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
            Data[] output = input.Select((x,i) => new {x = x,i = i}).GroupBy(x => x.i/2).Select(x => new Data() { upper = x.First().x,lower = x.Last().x}).ToArray(); 
        }
    }
    public class Data
    {
        public byte upper { get; set; }
        public byte lower { get; set; }
    }