bit manipulation in both directions

This is a discussion on bit manipulation in both directions within the C++ Programming forums, part of the General Programming Boards category; Hi.
I am trying to write a couple of algorithms that take in a 16 bit number, use a mask ...

bit manipulation in both directions

Hi.
I am trying to write a couple of algorithms that take in a 16 bit number, use a mask to move along the bits and if the mask & number = 1, do something.
The first thing to point out is this is going on a microcontroller. For that reason i am not looping through the entire 16 bit value in one go, I only do one at a time, so the program can return to whatever else it was doing in the mean time, and only do the next "bit" when a timer ticks so I need to save the last state of the changing variables between function calls.
I only however need the 12 Most significant bits, the 4 least significant bits I am using for something else, so my boundaries of the mask are 0x8000 and 0x10. One of my algorithms goes from left to right arpUp, and one goes from right to left:

So this checks if it is at the right boundary. If so, move the mask back to the left. and move the variable also.
The problem with that is it doesnt do "arpPlay()" when mask == 0x10 and (mask & chord)
I "could" do if (mask < 0x10) but I cant do the equivelent check for the arpDown function (if (mask > 0x8000)) because thats the end of the memory for the 16 bit value so I have:

I think that should be treated as a special case, because as you say, it is a 16-bit boundary. I wouldn't want to tell you to write something like

if ( mask <= 0x8000 && chord & mask )

The comparison itself is probably okay but instructions like mask <<= 1 would cause overflow, unlike what would happen when mask == 0x10, going in the other direction. No underflow there. Sorry if I've been unhelpful.

By special case, I mean we should probably stick to code that you have already, since you are already treating mask == 0x8000 as a special case, and it works. I can't really think of a logically equivalent way that is sufficiently safe. If you can guarantee that int is more than 16-bits, then you can try what I posted earlier with nothing to worry about.