简体   繁体   中英

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:

Type: Unisgned Char 1 byte

Name: Char 7 bytes

Mac: Char 13 bytes

Random Number: Char 7 bytes

Data: Char 50 bytes

This would be a structure with 1 byte chars, but the problem is the size:

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"):

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. 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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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