Question

Given enum:

typedef NS_OPTIONS(NSUInteger, BREBreathingProgram) {
    BREBreathingProgramPaceSlowest = 0,
    BREBreathingProgramPaceSlow = 1,
    BREBreathingProgramPaceMedium = 2,
    BREBreathingProgramPaceFast = 3,
    BREBreathingProgramPaceFastest = 4,
    BREBreathingProgramExcludeHold = 1 << 3,
};

To increment BreathingProgramPace I perform the following calculation:

breathingProgram = ((breathingProgram >> 3) & 1) << 3 | (breathingProgram & 3) + 1;

Is this the simplest way to do this?

Was it helpful?

Solution

Based on your 2nd comment to this answer I am rewriting the answer.

You have setup your enum so the first 3 bits represent a single value for the pace. You can have a value up to 7.

The fourth bit represents your "hold".

You wish to have some pace value and also some other bits set. You then wish to be able to increment that pace while keeping the other bits as they are.

This is simple.

breathingProgram++;

A simple increment is all you need. Example. Lets say your pace is set to "Slow" and the "hold" bit is set. This gives a value of 9 (1 for "slow" and 8 for "hold").

Now you wish to increment the pace to "medium". Simply incrementing from 9 to 10 does this.

While this works there is the risk that you could over increment the value and start messing with the flags.

A safer (and more complicated) way would be:

breathingProgram = (breathingProgram & 0xF8) | (((breathingProgram & 0x07) + 1) & 0x07);

This ensures that you can't do the increment past the allotted "pace" values and into the flags area. This would actually wrap the "pace" value back to zero if you went too far.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top