C# 是否有办法将具有 int 字段(byte、ushort、ulong 等)的对象编写为字节数组?
Does C# have a way to write an object with int fields (byte, ushort, ulong, etc.) as a byte array?
我正在尝试将仅具有 int 字段(ushort、ulong、uint、int 等)的对象转换为字节数组,其中每个 int 按其在对象中出现的顺序作为字节包含。
例如,如果我有一个形式为
的对象
obj = {subobj: {uint firstProp: 500, ushort secondProp: 12}, byte lastProp: 5}
那么我希望字节数组是
{0, 0, 1, 244, 0, 12, 5}
我尝试使用序列化创建这个字节数组(如 this answer), but I'm noticing there's a bunch of stuff before and after each byte. Based on this website 中所述,我相信这代表了数据库和文件,但我不想要这些。
我知道在 C++ 中我可以使用 reinterpret_cast<uint8_t*>(obj)
来获得想要的结果。在 C# 中是否有等效的方法来执行此操作?
您可以尝试这样做:
foreach(int value in obj)
{
byte lsbOfLsb = (byte)value;
byte msbOfLsb = (byte)(value >> 8);
byte lsbOfMsb = (byte)(value >> 16);
byte msbOfMsb = (byte)(value >> 24);
}
显然这只是想法。
您应该使用 for 循环而不是 foreach 并将所有元素解析为 int 例如.
另一种方法是使用
检查数据类型
typeof(value) //op 1
// OR
if(value is int) //e.g.
然后根据需要转换为字节。
我正在尝试将仅具有 int 字段(ushort、ulong、uint、int 等)的对象转换为字节数组,其中每个 int 按其在对象中出现的顺序作为字节包含。 例如,如果我有一个形式为
的对象obj = {subobj: {uint firstProp: 500, ushort secondProp: 12}, byte lastProp: 5}
那么我希望字节数组是
{0, 0, 1, 244, 0, 12, 5}
我尝试使用序列化创建这个字节数组(如 this answer), but I'm noticing there's a bunch of stuff before and after each byte. Based on this website 中所述,我相信这代表了数据库和文件,但我不想要这些。
我知道在 C++ 中我可以使用 reinterpret_cast<uint8_t*>(obj)
来获得想要的结果。在 C# 中是否有等效的方法来执行此操作?
您可以尝试这样做:
foreach(int value in obj)
{
byte lsbOfLsb = (byte)value;
byte msbOfLsb = (byte)(value >> 8);
byte lsbOfMsb = (byte)(value >> 16);
byte msbOfMsb = (byte)(value >> 24);
}
显然这只是想法。 您应该使用 for 循环而不是 foreach 并将所有元素解析为 int 例如. 另一种方法是使用
检查数据类型typeof(value) //op 1
// OR
if(value is int) //e.g.
然后根据需要转换为字节。