Bit Hacks Flashcards

1
Q

x AND 0’s

A

0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

x AND 1’s

A

x

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

x AND x

A

x

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

x OR 0’s

A

x

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

x OR 1’s

A

1’s

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

x OR x

A

x

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

x XOR 0’s

A

x

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

x XOR 1’s

A

~x

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

x XOR x

A

0’s

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

checking if the kth bit is set

A

n AND (1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

setting the kth bit

A

n OR (1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

clearing the kth bit

A

n AND ~(1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

toggling kth bit

A

n XOR (1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

toggling rightmost one bit

A

n AND n-1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

isolating rightmost one bit

A

n AND -n

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

isolating rightmost zero bit

A

~n AND n+1

17
Q

checking where number is a power of 2

A

(n AND n-1) == 0

18
Q

multiplying by a power of 2 (2^k)

A

n

19
Q

dividing by a power of 2 (2^k)

A

n&raquo_space; K

20
Q

finding the modulo of a given number

A

n AND 0x[hex value]

21
Q

creating mask for trailing zeros

A

(n AND -n) - 1

22
Q

reversing a binary number

A
unsigned int n, nReverse = n;
int s = sizeof(n);
for( ; n; n >>=1)
    nReverse |= n AND 1
    s--;
nReverse
23
Q

swap all odd and even bits

A

find even bits in N (evenN) = n AND 0xAA
find odd bits in N (oddN) = n AND 0x55
evenN&raquo_space;= 1
oddN

24
Q

check if 1 ints are equal WITHOUT comparison operators

A

!( i ^ j )

25
Q

detect if 2 ints have opposite signs

A

bool f = ((x^y)

26
Q

compute min of 2 ints, x and y

A

r = y XOR ((x XOR y) AND -(x

27
Q

compute max of 2 ints, x and y

A

r = x XOR ((x XOR y) AND -(x

28
Q

counting bits set - naive way

A

unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v

for (c = 0; v; v&raquo_space;= 1){
c += v AND 1;
}

29
Q

swapping values with XOR

A

define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))