我有一个 2 字节的 header 字段,其中前四位是数据包类型,其他 12 位是长度。但我不知道如何存储和检索这些值。
我在客户端使用 ms c++,在服务器端使用 java。客户端必须设置此值,服务器必须检索它。
谢谢
最佳答案
存储
unsigned short get_header(unsigned char type, unsigned short length)
{
return (static_cast<unsigned short>(type) << 12) | length;
}
检索(从无符号短)
unsigned short header = /* get 2 header bytes */
unsigned char type = header >> 12;
unsigned short length = header & 0xFFF;
检索(从 unsigned char[2])
unsigned char bytes[2] = /* get 2 header bytes */
unsigned char type = bytes[0] >> 4;
unsigned short length = bytes[0] & 0xF | bytes[1];
关于java - 如何设置不按字节边界划分的位值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2450279/