我正在开发一个工具,需要符合一个规范,这个规范要求在字节边界上将大量数据压缩到比特中。例如:2个字节编码2个字段,10位值、6位公差。其他字段可能跨越2-4个字节,并被分成更多的字段。
与其在C#中使用位域结构体(如C++中),我认为另一种选择是在发送/接收数据之前创建通用的位打包/解包函数,并使用标准类型(如byte、short、int、long等)在C#中处理所有数据。
我是C#新手,不确定最好的方法是什么。从我所阅读的资料来看,使用
我不想为所有可能的
我已经查看了
谢谢!
与其在C#中使用位域结构体(如C++中),我认为另一种选择是在发送/接收数据之前创建通用的位打包/解包函数,并使用标准类型(如byte、short、int、long等)在C#中处理所有数据。
我是C#新手,不确定最好的方法是什么。从我所阅读的资料来看,使用
unsafe
和指针是不被推荐的,但我的尝试使用通用类型失败了。private static bool GetBitsFromByte<T,U>(T input, byte count, out U output, byte start = 0) where T:struct where U:struct
{
if (input == default(T))
return false;
if( (start + count) > Marshal.SizeOf(input))
return false;
if(count > Marshal.SizeOf(output))
return false;
// I'd like to setup the correct output container based on the
// number of bits that are needed
if(count <= 8)
output = new byte();
else if (count <= 16)
output = new UInt16();
else if (count <= 32)
output = new UInt32();
else if (count <= 64)
output = new UInt64();
else
return false;
output = 0; // Init output
// Copy bits out in order
for (int i = start; i < count; i++)
{
output |= (input & (1 << i)); // This is not possible with generic types from my understanding
}
return true;
}
我会使用类似以下的方法从 data_in
中提取10个最低有效位(LSB)到 data_out
中,然后提取接下来的6个位到 next_data_out
中。
Uint32 data_in = 0xdeadbeef;
Uint16 data_out;
byte next_data_out;
if(GetBitsFromByte<Uint32,Uint16>(data_in, 10, out data_out, 0))
{
// data_out should now = 0x2EF
if(GetBitsFromByte<Uint32,byte>(data_in, 6, out next_data_out, data_out.Length))
{
// next_data_out should now = 0x2F
}
}
我不想为所有可能的
byte
, ushort
, uint
, ulong
组合编写函数,尽管我猜那是一种替代方法。我已经查看了
BitConverter
类,但那是用于操作字节数组而不是位。我也明白我不能做类似这样的事情:where T : INumeric
或 where T : System.ValueType
,所以我愿意听取建议。谢谢!