I want to write a function which extracts the first n bits starting by the MSB of a given uint16. I'm working with bitmasks for the first time and haven't found an elegant solution as far. I've written a similar function for the last n bits starting by the LSB which uses a bitmask looking like
(1 << n) - 1 and think this works.
If I have the value 0b1010001100000101 my function creates the bitmask (for n = 3 it looks like 0b111) and after that, uses the &-operator to check if the bits are present.
Which way should I use to get the first n bits?
I would be really happy if someone explain this to me because I want to understand how it works.
Thank you!
(uval << (16-n)) >> (16-n). If you mean the most significant bits they are(uval >> (16-n)) << (16-n). In each case, the unwanted bits are shoved off the end, and zeros are shifted back in.