Reputation: 6876
I'm having a difficult time understanding how to get these bits in the right order
my goal:
given the following inputs
char id = 0x02; //in binary => 0010
char somethingElse = 0xF; //in binary => 1111
how can I obtain the following output
char result = ?; //in binary 0010 1111 (id somethingElse)
Upvotes: 1
Views: 1000
Reputation: 3522
I would use a simpler shift operation unless the bits are often modified independently (like bits in the header of some format specification). In this case I would use a combination of a union and bit field. Here is a little program to do this
int main (int argc, const char * argv[])
{
@autoreleasepool {
union {
struct {
unsigned char id:4;
unsigned char somethingElse:4;
} split;
unsigned char combined;
} value;
value.split.id = 0x02;
value.split.somethingElse = 0xF;
NSLog(@"%02X", value.combined); // Outputs F2
}
return 0;
}
You might want to invert the order of id and somethingElse if this is not the order you want.
Upvotes: 0
Reputation: 10346
char id = 0x02; //in binary => 0010
char somethingElse = 0xF; //in binary => 1111
char result = (id<<4) | somethingElse;
Upvotes: 2