Reputation: 307
I have a requirement to have an unsigned 3 byte type in C. I am looking for a way to pack them into a single unsigned int.
Is this safe or does this need to be stored inside an array/structure for the 24 bit size?
unsigned int pack_3Byte(unsigned char b1, unsigned char b2, unsigned char b3)
{
return (b1 << 16) | (b2 << 8) | (b3);
}
Upvotes: 1
Views: 265
Reputation: 6762
Your code is correct but like Olaf says you should use the types uint8_t and uint32_t to ensure that your types are really the width you expect them to be.
This may not be a problem right now, but you should also be aware that the bytes in an integer are stored in different order on different processors. This is called endianness.
Upvotes: 1