我需要轉換使用大量位元組操作的 C# 應用程式。
一個例子:
public abstract class BinRecord
{
public static int version => 1;
public virtual int LENGTH => 1 7 8 2 1; // 19
public char type;
public ulong timestamp; // 7 byte
public double p;
public ushort size;
public char callbackType;
public virtual void FillBytes(byte[] bytes)
{
bytes[0] = (byte)type;
var t = BitConverter.GetBytes(timestamp);
Buffer.BlockCopy(t, 0, bytes, 1, 7);
Buffer.BlockCopy(BitConverter.GetBytes(p), 0, bytes, 8, 8);
Buffer.BlockCopy(BitConverter.GetBytes(size), 0, bytes, 16, 2);
bytes[18] = (byte)callbackType;
}
}
基本上每秒呼叫 100 次BitConverter。Buffer.BlockCopy
有幾個類繼承自上面的基類,執行更具體的任務。例如:
public class SpecRecord : BinRecord
{
public override int LENGTH => base.LENGTH 2;
public ushort num;
public SpecRecord() { }
public SpecRecord(ushort num)
{
this.num = num;
}
public override void FillBytes(byte[] bytes)
{
var idx = base.LENGTH;
base.FillBytes(bytes);
Buffer.BlockCopy(BitConverter.GetBytes(num), 0, bytes, idx 0, 2);
}
}
我應該研究 C 中的什么方法?
uj5u.com熱心網友回復:
在我看來,最好的選擇是實際使用 C - 用于memcpy復制任何物件的位元組。
您的上述代碼將被重寫如下:
void FillBytes(uint8_t* bytes)
{
bytes[0] = (uint8_t)type;
memcpy((bytes 1), &(((uint8_t*)(t))[1]), sizeof(uint64_t) - 1);
memcpy((bytes 8), &p, sizeof(double));
memcpy((bytes 16), &size, sizeof(uint16_t));
bytes[18] = (uint8_t)callbackType;
}
在這里,我使用uint8_t、uint16_t和uint64_t作為 、 和 型別的byte替代ushort品ulong。
請記住,您的時間戳副本不能移植到大端 CPU - 它會切斷最低位元組而不是最高位元組。解決這個問題需要手動復制每個位元組,如下所示:
//Copy a 7 byte timestamp into the buffer.
bytes[1] = (t >> 0) & 0xFF;
bytes[2] = (t >> 8) & 0xFF;
bytes[3] = (t >> 16) & 0xFF;
bytes[4] = (t >> 24) & 0xFF;
bytes[5] = (t >> 32) & 0xFF;
bytes[6] = (t >> 40) & 0xFF;
bytes[7] = (t >> 48) & 0xFF;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/447219.html
