2017-05-31 67 views
0

我有4字节的数据流,我知道什么时候我想分割它们,并将它们分配给不同的变量。请记住我收到的数据是十六进制格式。比方说,我如何解码4个字节的数据将它们相应地拆分并将它们分配给一个有意义的变量?

P_settings 4bytes p_timeout [6:0] 
        p_s_detected[7] 

        p_o_timeout [14:8] 
        p_o_timeout_set [15] 

        override_l_lvl [23:16] 
        l_b_lvl [31:24] 

以上P_settings为4个字节,我想他们分裂成字节像位p_timeout [6:0] requires 7 bits of those 4 byte.

目前,我已经试过is..for只是一个字节拆分成位实施。

var soch = ((b_data>> 0)& 0x7F); if i want first 7 bits 

我怎么办呢4字节流这样

+0

你有没有想过使用一个uint的?它是32位。一般来说,如果你想要的位在一个4字节的值中被分成不同的字节,你不需要担心它们在单独的字节中。即字节结果=((b_data&0x000ff000)>> 12)会将位12-20拉出来。 –

回答

2

try代码。你说输入是一个流。

public class P_Settings 
    { 
     byte p_timeout; //[6:0] 
     Boolean p_s_detected; //[7] 

     byte p_o_timeout; // [14:8] 
     Boolean p_o_timeout_set; // [15] 

     byte override_l_lvl; //[23:16] 
     byte l_b_lvl; //[31:24] 

     public P_Settings(Stream data) 
     { 
      byte input = (byte)(data.ReadByte() & 0xff); 
      p_timeout = (byte)(input & 0x7F); 
      p_s_detected = (input & 0x80) == 0 ? false : true; 

      input = (byte)(data.ReadByte() & 0xff); 
      p_o_timeout = (byte)(input & 0x7F); 
      p_o_timeout_set = (input & 0x80) == 0 ? false : true; 

      override_l_lvl = (byte)(data.ReadByte() & 0xff); 
      l_b_lvl = (byte)(data.ReadByte() & 0xff); 
     } 
    } 
-1

因此,原来它是我想象的要容易.. 1)单字节将它们分开,并把它们放在一个缓冲和&独立操作它们,你会得到的数据。感谢所有的支持。

**

   byte input = (byte)(buffer[10]);//1 byte 
       var p_timeout = (byte)(input & 0x7F); 
       var p_s_detected = (input & 0x80) == 0 ? false : true; 

       input = (byte)(buffer[11]);//1 byte 
       var p_o_timeout = (byte)(input & 0x7F); 
       var p_o_timeout_set = (input & 0x80) == 0 ? false : true; 

       var override_l_lvl = (byte)(buffer[12] & 0xff);//1 byte 
       var l_b_lvl = (byte)(buffer[13] & 0xff); //1 byte 

**

+0

好吧,这几乎是jdweng正确答案的精确复制粘贴。 – Herb

相关问题