Reputation: 18552
Suppose I have one long long int and want to take its bits and construct four unsigned short ints out of it.
Particular order doesn't matter much here.
I generally know that I need to shift bits and truncate to the size of unsigned short int. But I think I may make some weird mistake somewhere, so I ask.
Upvotes: 5
Views: 2680
Reputation: 223183
#include <stdint.h>
#include <stdio.h>
union ui64 {
uint64_t one;
uint16_t four[4];
};
int
main()
{
union ui64 number = {0x123456789abcdef0};
printf("%x %x %x %x\n", number.four[0], number.four[1],
number.four[2], number.four[3]);
return 0;
}
Upvotes: 12
Reputation: 89165
(unsigned short)((((unsigned long long int)value)>>(x))&(0xFFFF))
where value
is your long long int
, and x
is 0, 16, 32 or 48 for the four shorts.
Upvotes: 3
Reputation: 25727
union LongLongIntToThreeUnsignedShorts {
long long int long_long_int;
unsigned short int short_ints[sizeof(long long int) / sizeof(short int)];
};
That should do what you are thinking about, without having to mess around with bit shifting.
Upvotes: 2