简体   繁体   English

如何在 C 中创建字节数据包?

[英]How can I create a byte packet in C?

I just wanted to know how could I create a byte packet in C. I need a packet like this:我只是想知道如何在 C 中创建一个字节数据包。我需要一个这样的数据包:

Type: Unisgned Char 1 byte类型: Unsigned Char 1 字节

Name: Char 7 bytes名称:字符 7 字节

Mac: Char 13 bytes Mac:字符 13 字节

Random Number: Char 7 bytes随机数: Char 7 字节

Data: Char 50 bytes数据:字符 50 字节

This would be a structure with 1 byte chars, but the problem is the size:这将是一个具有 1 字节字符的结构,但问题是大小:

struct PDU{
    unsigned char code;
    char name;
    char mac;
    char RNumber;
    char data;
}

How could I change the size of the chars?我怎样才能改变字符的大小?

Thanks谢谢

You cannot change the size of char - but you can make lists of char s long enough for each of the items (these are called "arrays"):您无法更改char的大小 - 但您可以为每个项目制作足够长的char列表(这些称为“数组”):

struct PDU{
    unsigned char code;
    char name[7];
    char mac[13];
    char RNumber[7];
    char data[50];
};

Beware of structure padding : a C compiler is free to add padding bytes between each of these items.注意结构填充:C 编译器可以随意在这些项之间添加填充字节。 It may do so because accessing 'word aligned' data usually is faster than 'any byte'.这样做可能是因为访问“字对齐”数据通常比“任何字节”更快。 You can instruct the compiler to not do so by adding a special compiler instruction before this structure, usually (check your compiler manual!) something like您可以通过在此结构之前添加特殊的编译器指令来指示编译器不要这样做,通常(检查您的编译器手册!)类似

#pragma pack(1)

If there are other structure definitions after this one that don't need their padding removed, look up the instruction to restore Normal Services again and add it below this strcture definition.如果在此之后还有其他不需要删除填充的结构定义,请再次查找恢复普通服务的说明,并将其添加到此结构定义下方。

When copying data into this structure, it is absolutely vital that you do not copy 'out of bounds' and overwrite the data in the next item.将数据复制到此结构中时,绝对重要的是不要复制“越界”并覆盖下一项中的数据。 (That goes for all programs in C but I might as well mention it again.) (这适用于所有 C 语言程序,但我不妨再提一次。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM