Friday, May 15, 2009

Several Trivia about Bit Operation

Shift and division: Bit right/left shift to implement arithmetic division and multiplication by a power of 2. It works with unsigned types, and signed types for left shift. Division with signed types rounds toward 0, but right shift rounds to negative infinite.

int a, b, c;
a = -1;
b = a >> 1; // b is -1;
c = a / 2; // c is 0;

In two’s complement, zero is not the only number that is equal to its negative, same happens to the value with just the highest bit set

if (x < 0)  x = -x;
// assume x is always positive
// but is it wrong

A shift by more than BITS_PER_LONG-1 is undefined by the C-standard.

int foo (int k)
int t = ABC >> (BIT_PER_INT - k);
return t; // when k == 0, undefined
if (k == 0) t = 0; // add this before return in foo

No comments:

Post a Comment