Skip to content

Instantly share code, notes, and snippets.

@jeffbailey
Last active August 29, 2015 13:56
Show Gist options
  • Save jeffbailey/891bb556ea5fd6d21e5a to your computer and use it in GitHub Desktop.
Save jeffbailey/891bb556ea5fd6d21e5a to your computer and use it in GitHub Desktop.
Example of setting, getting, toggling and clearing bits. Source: http://iosdevelopertips.com/c/creating-bit-fields-in-c-and-objective-c.html
#define BIT_ONE 1
#define BIT_TWO 2
#define BIT_THREE 4
#define BIT_FOUR 8
int flag = 0;
// Set bits
flag |= BIT_ONE | BIT_THREE;
NSLog(@"Bits: %@", [self intToBinaryString:flag]);
// Clear bits
flag &= ~(BIT_ONE | BIT_THREE);
NSLog(@"Bits: %@", [self intToBinaryString:flag]);
// Toggle bit
flag ^= (BIT_ONE | BIT_THREE);
NSLog(@"Bits: %@", [self intToBinaryString:flag]);
// Check bits
if (flag & (BIT_ONE | BIT_THREE))
NSLog(@"Bits set");
else
NSLog(@"Bits not set");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment