Search code examples
objective-cbinarybit-manipulation

Getting Position of the Leftmost Bit


I have a 5 bit integer that I'm working with. Is there a native function in Objective-C that will let me know which bit is the leftmost?

i.e. I have 01001, it would return 8 or the position.


Solution

  • NSInteger value = 9;
    NSInteger shift = 1;
    for(NSInteger bit = value; bit > 1; bit = value >> ++shift);
    NSInteger leftmostbit = 1 << shift;
    

    Works for every number of bits.