user10792793
user10792793

Reputation:

Setting all Bits to the Least Significant Bit

If I have a x of type int, how can I get the value of x's LSB and set all of the other bits in the number to that LSB?

I've been messing around with bitwise and logical operators for a little bit (no pun intended) and I understand how they function.

The shift operators x >> 3 and x << 3 shift the bits of x three spaces left and right respectively, and I know we can use operators like ^ | and & for messing around with manipulating bits. I'm having trouble understanding the logic for this particular problem.

EDIT: The operators which we are allowed to use for this are ! ~ & ^ | + << >>

Upvotes: 0

Views: 3373

Answers (3)

Peter
Peter

Reputation: 393

if (x & 1) {x = 4294967295 } else { x = 0 }. In other words if x is odd the LSB is 1 so set x to the biggest possible 32 bit unsigned integer (all bits set to 1), otherwise if x is even the LSB is zero, so set x to be zero. But wait, it is a signed integer, setting all the bits to 1 would mean the signed bit is set. So change that to be: if (x & 1) { x = -1 } else { x = 0 }. As commented by Eugene one can then just use -(x & 1).

Upvotes: 0

0___________
0___________

Reputation: 67516

You all assume - but recently I was helping examining students and the the question - find the LSB or value of the LSB meant the lowest bit set in the number. It make a bit more sense making the task less trivial and obvious.

in this case:

to get value of the LSB - z & (~z+1)

 z = ~(z & (~z+1));

Upvotes: -2

Petr Skocik
Petr Skocik

Reputation: 60068

Very literally:

type x /*=some value*/;
_Bool lsb = x&1;
x = lsb ? ~(type)0 : (type)0;

Optimizing compilers on 2's complement architectures make it branch-less and equivalent to:

 type x /*=some value*/;
_Bool lsb = x&1;
 x = -lsb;

(or -(x&1) without the intermediary lsb variable.)

https://gcc.godbolt.org/z/2NXFpS

Upvotes: 5

Related Questions