C# 从十六进制数据中获取信息
我有这个十六进制数据:
byte[] data = new Byte[] {
0xC1, 0x3A, 0x00, 0x01, 0x5D, 0xDA, 0x47, 0x53, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xF0, 0xFC, 0x12, 0x00, 0x00, 0x00
};
我有 C++ 结构:
struct SERVICE
{
unsigned char c;
unsigned char size;
unsigned char headcode;
unsigned char Type;
unsigned short Port;
char ServiceName[50];
unsigned short ServiceCode;
};
我的问题是: 如何从数据中获取 ServiceName、Port 等...?
抱歉我的英语不好
I have this hexadecimal data:
byte[] data = new Byte[] {
0xC1, 0x3A, 0x00, 0x01, 0x5D, 0xDA, 0x47, 0x53, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xF0, 0xFC, 0x12, 0x00, 0x00, 0x00
};
I have C++ struct:
struct SERVICE
{
unsigned char c;
unsigned char size;
unsigned char headcode;
unsigned char Type;
unsigned short Port;
char ServiceName[50];
unsigned short ServiceCode;
};
My question is: How to get from data ServiceName, Port and etc...?
Sorry for my bad english
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一种实现方法:
假设二进制数组使用与您的体系结构相同的字节顺序。如果不是这种情况,您可以使用 MiscUtil 库中的 EndianBinaryReader。
编辑:这也是一个很好的解决方案,完全避免了读者。但是,您无法直接指定用于字符串的编码,并且结构的内存布局必须与字节数组中使用的布局相匹配。
Here is one way to do it:
This assumes, that the binary array uses the same Endianess as your architecture. If that is not the case you can use the EndianBinaryReader from the MiscUtil library.
Edit: this is also a nice solution, that avoids the reader altogether. You can't directly specify the encoding to use for the string however and the memory layout of the structure has to match the layout used in the byte array.
首先,确定您的字节编码是小端还是大端。然后,将字段一一解压(C 示例)
注意:这通常写为移动数据指针,而不是使用“i”作为索引,但我将其保留为这种形式,以便于迁移到 C#。
First, Decide if your byte encoding is little or big endian. Then, unpack fields one by one (C example)
NOTE: This is usually written as moving the data pointer instead of using "i" as an index, but I left it in this form for ease of moving to C#.
从问题中,我无法找出你想如何实现这一点,但这是 C# 结构。
您可以定义如下结构
From the question, I could not find out how you want to achieve this but this is the C# structure.
You can define the structure as below