views:

249

answers:

6

I recently saw an interview question asking the following:

Given a 32 bit number, write pseudo code to flip the second last bit

What is the best/easiest way to do this?

A: 

use a bitwise XOR operator?

Yellowfog
+5  A: 
#define MASK 0x00000002 

new = old ^ MASK

Daniel Băluţă
+2  A: 

Exclusive Or with 2. For example i = i ^ 2

leonm
+3  A: 
a = 0x80000000; // the second last bit set
if( i & a == 0) // not set in i -> set it
  i |= a;
else // set -> un-set it in i
 i &= ~a;

edit: arg, of course you can XOR it :-) But 2 is the second bit not the second last bit. Maybe better to talk about MSB and LSB.

Code Clown
+3  A: 
X ^ (1<<n) will toggle the state of nth bit in the number X.
Prabhu Jayaraman
A: 

I see some answers interpret "last bit" as MSB, others as LSB. Perhaps they're looking for candidates smart enough to pause and ask for clarification before cranking out code. That's very important in real-world work.

DarenW