Sanyam Jain
Sanyam Jain

Reputation: 113

Bits shifted by bit shifting operators(<<, >>) in C, C++

can we access the bits shifted by bit shifting operators(<<, >>) in C, C++? For example: 23>>1 can we access the last bit shifted(1 in this case)?

Upvotes: 0

Views: 187

Answers (4)

Felice Pollano
Felice Pollano

Reputation: 33242

It worth signal that on MSVC compiler an intrinsic function exists: _bittest

that speeds up the operation.

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254431

No, the shift operators only give the value after shifting. You'll need to do other bitwise operations to extract the bits that are shifted out of the value; for example:

unsigned all_lost  = value & ((1 << shift)-1);  // all bits to be removed by shift
unsigned last_lost = (value >> (shift-1)) & 1;  // last bit to be removed by shift
unsigned remaining = value >> shift;            // lose those bits

Upvotes: 3

Daerst
Daerst

Reputation: 973

By using 23>>1, the bit 0x01 is purged - you have no way of retrieving it after the bit shift.

That said, nothing's stopping you from checking for the bit before shifting:

int  value   = 23;
bool bit1    = value & 0x01;
int  shifted = value >> 1;

Upvotes: 2

user3386109
user3386109

Reputation: 34829

You can access the bits before shifting, e.g.

value  = 23;          // start with some value
lsbits = value & 1;   // extract the LSB
value >>= 1;          // shift

Upvotes: 0

Related Questions