我正在研究一個工具,該工具必須符合跨越字節邊界將大量數據打包到數據位的規範。例如:2個字節編碼2個字段,10位值,6位容差。其他字段可能會跨越2-4個字節並分解成更多字段。C# - 編寫處理位操作的通用方法
而不是與C#爭鬥並嘗試獲取位域的結構(比如在C++中),我想另一種方法是在接收數據之前/之後創建泛型位打包/解包功能,並使用C#使用標準類型:字節,短,int,長等。
我是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;
}
我會打電話的是這樣的方法來拉動10位(LSB從)從data_in
變爲data_out
,接下來的6位從data_in
變成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
,所以我願意提供建議。
謝謝!
您是否考慮調用非託管c/C++代碼?它可能更容易。 – Jay
@Jay我希望能夠在C#中完成所有工作,但如果所有其他工作都失敗了,那就是回退計劃。 – sbtkd85
@neoistheone謝謝,更新 – sbtkd85