将一个字节中的两个 Int4 读入两个单独的字节,反之亦然

Reading Two Int4 from a Byte into two Seperate Bytes and Vice Versa

好吧,这听起来可能很荒谬,但作为个人项目,我正在尝试 re-create C# 中的 TCP 网络协议。

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

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

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

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

类似于:

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

应该做你想做的。

是的,按位 操作将执行:

拆分:

byte header = ...

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

合并:

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