从NamedPipeClientStream移动位

时间:2015-05-11 23:20:12

标签: c# bit-shift

我目前正在尝试编写一个通过NamedPipeClientStream读取数据的同步串行协议。然后需要持续监视该数据的同步字符(十六进制22),这些字符可能在字节边界上,也可能不在字节边界上,并相应地移位数据以确保接收的其他数据在帧中。

我已经制作了几个场景的原型,包括一个位数组,并使用由发布到此站点的人设计的BitStream对象,所有这些对象看起来都很麻烦,而且很可能非常低效。

在找到同步字符后,发送的数据将继续进入,因此我必须继续将输入数据添加到已移位的位流的末尾。

1 个答案:

答案 0 :(得分:0)

也许是这样的

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader("filename");
            UInt16 chr = (UInt16)reader.Read();
            UInt16 word = 0;
            int shift = -1;

            while (shift == -1)
            {
                word = (UInt16)((UInt16)(word << 8) | chr);
                shift = TestSync(chr, word);
            }
            while ((chr = (UInt16)reader.Read()) >= 0)
            {
                word = (UInt16)((UInt16)(word << 8) | chr);
                byte newChar = (byte)((word >> shift) & 0xff);

            }


        }
        static int TestSync(UInt16 chr, UInt16 word)
        {
            int results = -1;


            if((UInt16)(word & 0xff) == 0x11) return 0;
            if((UInt16)(word & 0xff) == 0x22) return 1; 
            if((UInt16)(word & 0xff) == 0x44) return 2;
            if((UInt16)(word & 0xff) == 0x88) return 3;
            if((UInt16)(word & 0x1fe) == 0x110) return 4;
            if((UInt16)(word & 0x3fc) == 0x220) return 5;
            if((UInt16)(word & 0x7f8) == 0x440) return 6;
            if ((UInt16)(word & 0xff0) == 0x880) return 7;

            return results;
        }
    }
}
​
相关问题