【问题标题】:Reading Two Int4 from a Byte into two Seperate Bytes and Vice Versa将两个 Int4 从一个字节读入两个单独的字节,反之亦然
【发布时间】:2021-02-01 21:25:05
【问题描述】:

好吧,这听起来可能很荒谬,但作为个人项目,我正在尝试用 C# 重新创建 TCP 网络协议。

收到的每个 TCP 数据包都有一个头,该头必须以两个 Int4 (0 - 15) 开头,形成一个字节。我认为使用按位运算符我已经从字节中提取了两个 Int4:

Byte firstInt4 = headerByte << 4;
Byte secondInt4 = headerByte >> 4;

问题是我现在需要能够将两个 Int4 写入一个 Byte,但我不知道该怎么做。

【问题讨论】:

    标签: c# byte bitwise-operators


    【解决方案1】:

    是的,按位操作即可:

    拆分:

    byte header = ...
    
    byte firstInt4 = (byte) (header & 0xF);     // 4 low  bits
    byte secondInt4 = (byte) (headerByte >> 4); // 4 high bits
    

    合并:

    byte header = (byte) ((secondInt4 << 4) | firstInt4);   
    

    【讨论】:

      【解决方案2】:

      int4 被称为“nibble”:半字节是 nibble。 :)

      类似:

      combinedByte = hiNibble;
      combinedByte << 4;  // Make space for second nibble.
      combinedByte += loNibble;
      

      应该做你想做的。

      【讨论】:

      • | 是执行此操作的规范方法,而不是 +=
      猜你喜欢
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      • 2014-01-09
      • 2014-04-16
      • 1970-01-01
      • 2012-03-06
      相关资源
      最近更新 更多