isa56k
isa56k

Reputation: 145

Calculate bits set in NSData. Maybe use enum? Objective C

I'm not sure how to go about solving this.

I have a byte of data that is received that defines which colour LEDs are available in a piece of hardware.

There are 4 LEDs Red, Green, Blue and White.

bit 0 = Red (1 On | 0 Off)
bit 1 = Green (1 On | 0 Off)
bit 2 = Blue (1 On | 0 Off)
bit 3 = White (1 On | 0 Off)
bit 4 = Unused / Future Use
bit 5 = Unused / Future Use
bit 6 = Unused / Future Use
bit 7 = Unused / Future Use

If I get an int value 11 from the hardware the bit mask is: 0000 1011 (Little Endian) so the LEDs in use are White, Green and Red.

If I got an int value 15 then all LEDs are in use, if it is 7 all but white are in use.

What I'm trying to work out is a good way to evaluate the bits that are set and then display which LEDs are available.

What is the best way to evaluate which bits are set and then display it in NSString to the user.

Should I use an enum as below and then try to evaluate that, how would I do the evaluation?

typedef enum {

    RedLEDAvailable    = 1 << 0,
    GreenLEDAvailable  = 1 << 1,
    BlueLEDAvailable   = 1 << 2,
    WhiteLEDAvailable  = 1 << 3

} LEDStatus;

Thanks in advance.

Upvotes: 0

Views: 145

Answers (1)

Rob Sanders
Rob Sanders

Reputation: 5347

Yes you have a bit mask for each LED and then you can compare the value you get from the hardware to determine which LEDs are available.

Evaluating bit masks is easy you either use the & or the | operators to "and" or "or" the bits together.

As an example of how this works take the numbers 0001 and 0101 (in binary). If you | them together the computer examines each bit in turn of both numbers sees if EITHER one or both numbers has a 1 in each position and if that is the case then a 1 goes in that position for the result.

If you & them together then a 1 is put in that position only if BOTH bit masks have a 1 there.

Sorry if this is a bit garbled but basically this means that 0001 & 0101 = 0001. And 0001 | 0101 = 0101.

This means that if you want to COMBINE bit masks you can use the | operator and if you want to evaluate them you can use the & operator.

E.g.:

if ((LEDsAvailable & RedLEDAvailable) == RedLEDAvailable) {
    // Red light ready
}
else {
    // Red light not ready
}

In terms of displaying this as a string to the user you can just create an NSMutableString and append the appropriate messages depending on how your bit mask evaluates.

Upvotes: 2

Related Questions