开发者

Interview: Flipping Bits

开发者 https://www.devze.com 2023-01-06 01:10 出处:网络
I recently saw an interview question asking the following: Given a 32 bit number, write pseud开发者_运维问答o

I recently saw an interview question asking the following:

Given a 32 bit number, write pseud开发者_运维问答o code to flip the second last bit

What is the best/easiest way to do this?


#define MASK 0x00000002 

new = old ^ MASK


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.


X ^ (1<<n) will toggle the state of nth bit in the number X.


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


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.


use a bitwise XOR operator?

0

精彩评论

暂无评论...
验证码 换一张
取 消