Mixing Uint8 and int16 in Struct

Tip / Sign in to post questions, reply, level up, and achieve exciting badges. Know more

cross mob
AnWa_1259496
Level 4
Level 4
Welcome! 50 replies posted 25 replies posted

I have a USB report structure:

   

Uint8 Buttons

   

int16 Xaxis

   

int16 Y axis

   

 

   

But the compiler assigns 2 bytes for the Unit8 instead of one so the USB packet is incorrect. Is this expected?

0 Likes
8 Replies
Bob_Marlowe
Level 10
Level 10
First like given 50 questions asked 10 questions asked

Since the int16s have to be aligned on a word boundary this is expected. You could try to put your uint8 as the last element in the structure, then the size will be 5 bytes.

   

 

   

Bob

0 Likes
ETRO_SSN583
Level 9
Level 9
250 likes received 100 sign-ins 5 likes given

Or make it a word and cast it back to int8 when you use it.

   

 

   

Regards, Dana.

0 Likes
AnWa_1259496
Level 4
Level 4
Welcome! 50 replies posted 25 replies posted

 But the data format has to be as stated because it needs to match the USB descriptor.

   

I guess I will need to make it all int8 and programatically split the 16 bits into 8s.

0 Likes
odissey1
Level 9
Level 9
First comment on KBA 1000 replies posted 750 replies posted

 You need to make a 'packed' type structure, so it will be exactly 5 bytes long

   

See example below, now sizeof(MyStruc)=5.

   

odissey1

   

 

   

pragma pack(push, 1) // exact fit - no padding

   

struct MyStruct { uint8 a; uint16 b; uint16 c; };

   

#pragma pack(pop) //back to whatever the previous packing mode was 

0 Likes
Bob_Marlowe
Level 10
Level 10
First like given 50 questions asked 10 questions asked

Have a look at the packed attribute for structs.

   

 

   

Bob

0 Likes
HeLi_263931
Level 8
Level 8
100 solutions authored 50 solutions authored 25 solutions authored

To pack a struct:

   

typedef struct
{
    uint8 first;
    int16 second;
} __attribute__ ((__packed__)) data;

0 Likes
AnWa_1259496
Level 4
Level 4
Welcome! 50 replies posted 25 replies posted

 The method posted by Odissey1 worked.

   

Using the "packed" attribute results in a warning: attribute "packed" ignored..

0 Likes
odissey1
Level 9
Level 9
First comment on KBA 1000 replies posted 750 replies posted

This one might work:

   

typedef myStruct
{
    uint8 first;
    int16 second;
} __attribute__ ((packed));

   

myStruct data;

0 Likes