I\'m new to working with bits. I\'m trying to work with an existing protocol, which can send three different types of messages.
Type 1 is a 16-bit structure:
<You shouldn't use C structure bitfields because the physical layout of bitfields is undefined. While you could figure out what your compiler is doing and get your layout to match the underlying data, the code may not work if you switch to a different compiler or even update your compiler.
I know it's a pain, but do the bit manipulation yourself.
You don't have to do this, this is where the union keyword comes in - you can specify all the bits out at the same time, or by referring to the same bits with a different name, set them all at once.
You can do it with a series of shifts, and
s, and or
s. I have done the 10-bit index part for Type 2:
unsigned int i = 252;
analog a = (analog)(((i << 16) & 0x7f0000) | (i << 17) & 0x7000000);
Essentially, what this code does is shift the 10 bits of interest in int i
to the range 16 - 25, then it and
s it with the bitmask 0x7f0000
to set bits 22 - 31 to zero. It also shifts another copy of the 10 bits to the range 17 - 26, then it and
s it with the bitmask 0x7000000
to set bits 0 - 22 and 26 - 31 to zero. Then it or
s the two values together to create your desired zero-separated value.
.. I'm not absolutely sure that I counted the bitmasks correctly, but I hope you've got the idea. Just shift, and-mask, and or-merge.
Edit: Method 2:
analog a;
a.sig1 = (i & 0x7f); // mask out bit 8 onwards
a.sig2 = ((i<<1) & 0x700); // shift left by one, then mask out bits 0-8
On second thought method 2 is more readable, so you should probably use this.