際際滷

際際滷Share a Scribd company logo
BIT HACKS
lancer1268
BITWISE OPERATION
Binary number
? 19 10 = 10011 2
? 7 10 = 111 2
AND
? int a = 3 = 011 2
int b = 5 = 101 2
? a & b = 1 = 001 2
011
& 101
--------
= 001
OR
? int a = 3 = 011 2
int b = 5 = 101 2
? a | b = 7 = 111 2
011
| 101
--------
= 111
XOR (Exclusive OR)
? int a = 3 = 011 2
int b = 5 = 101 2
? a ^ b = 6 = 110 2
011
^ 101
--------
= 110
NOT
? 1001
? 邪O峪嗤4bit
? a = 3 = 0011 2
~a = 12 = 1100 2
Shift
? 屎 right-shift
a = 11 = 1011 2
a >> 2 = 2 = 0010 2
? 屎 left-shift
a = 11 = 1011 2
a << 2 = 2 = 1100 2
TRICKS
屎
? 屎0 -1
int sign = a >> 31;
? 屎1 -1
int sign = 1 | ( a >> 31 );
? 屎1 巣0 -1
int sign = ( a != 0 ) | ( a >> 31 );
音揖屎
? 麻ラ採登猩狃察⇒弘´
? 音揖屎true 揖屎false
bool diff = ( a ^ b ) >> 31 ;
頁音頁 2 議膣
? 箭徨8 ? ??? , 7 ? ??
? 屎屁
bool result = ( a & ( a C 1 ) ) == 0 ;
? 深]0
bool result = a && !( a & ( a C 1 ) ) ;
麻嗤ラ bit 頁 1
? 児A圭隈
for( cnt = 0 ; a ; a >>= 1 ) cnt += a & 1 ;
? 臥燕
cnt = table256[ a & 0xff ] +
table256[ ( a >> 8 ) & 0xff ] +
table256[ ( a >> 16 ) & 0xff ] +
table256[ a >> 24 ];
吏貧函2議膣
? 箭徨 5 ? 8
? --a ;
a |= a >> 1 ;
a |= a >> 2 ;
a |= a >> 4 ;
a |= a >> 8 ;
a |= a >> 16 ;
++a ;
恷嘔議 1
? 匆出 lowbit
? 箭徨 010010 2 ? 000010 2
101000 2 ? 001000 2
? lowbit(x) = x & ( -x ) ;
BITMASK
鹿栽
? 嗤匯喇 0, 1, ? , ? ? 1 撹議鹿栽 ?
? 厘辛參喘匯 ? bit議屁 ? ? 躅輅 ?
? 及 ?  bit  1 旗燕 ? 壓 ? e中楻吽毅
? 箭徨
? = 5
? = 0, 2, 3 ? ? ? = 01101 2
?>
= 1, 2, 4 ? ? ?> = 10110 2
械喘議鹿栽
? ?1 = 0, 1, ? , ? ? 1
? ?1
= ( 1 << n ) C 1 ;
? ?2 = ?
? ?2
= 1 << i ;
Set operations
? o低鹿栽低辛參恂匯乂並
C 鹿 Union
C 住鹿 Intersection
C ΨQ餓 Symmetric Difference
C 登牋根 Inclusion
鹿 Union
? 鹿凪祥頁壓恂 bitwise OR
? ? ?“?> = ? ? | ? ?>
? 箭徨
? = 5
? = 0, 3, 4 ? ? ? = 11001 2
?>
= 0,1,4 ? ? ?> = 10011 2
? “ ?>
= 0,1,3,4
? ? ?“?> = 11011 2
住鹿 Intersection
? 住鹿凪祥頁壓恂 bitwise AND
? ? ?”?> = ? ? & ? ?>
ΨQ餓 Symmetric Difference
? ΨQ餓凪祥頁壓恂 bitwise XOR
? ? ?Δ?> = ? ? ^ ? ?>
登牋根 Inclusion
? 登牋根辛參心住鹿參瘁嗤]嗤
? ? ? ?> ? = ? ” ?> = ? ?
bool inc = ? ? & ? ?> == ? ?;
MORE TRICKS
旦e徨鹿
? 嗤r俶勣旦e徨鹿栽
? 箭徨
? = 0, 1, 3
?, 0 , 1 , 3 , 0,1 , 0,3 , 1,3 , 0,1,3
0000, 0001, 0010, 1000,0011, 1001, 1010, 1011
旦e徨鹿 - simplified
? 枠深]曳^竜聴羆
? 朕烹挫凝e ? = 0, 1, ? , ? ? 1 議徨鹿栽
? 恬隈詐擁 0 ~ 2 ?
? 1
C 0...000
C 0...001
C 0...010
C 0...011
C ...
C 1...111
旦e徨鹿 - original
? 朕烹挫凝e ? 議徨鹿栽
? 嗤匯乂喘音欺議 bit 奕Nk芯脳猷子深]麿
for ( int sub = sup ; ; sub = ( sub - 1 ) & sup ) {
// do something
if ( sub == 0 ) break ;
}
旦e徨鹿 2
? 嗤r俶勣旦e寄弌 ? 議徨鹿栽
? 箭徨
? = 0, 1, 3 , ? = 2
0,1 , 0,3 , 1,3
0011, 1001, 1010
旦e徨鹿 2 - simplified
? 枠深] ? = 0, 1, ? , ? ? 1
? 箭徨
int lower = ( 1 << k ) - 1, upper = 1 << n ;
for ( int comb = lower ; comb < upper ; ) {
// do something
comb = next_permu( comb ) ;
}
旦e徨鹿 2 - simplified
? 嶷c頁孀竃和匯電双徭失D心心
int next_permu( int p ) {
int x = lowbit( p ), y = p + x ;
return y | ( ( p & ~y ) / x >> 1 ) ;
// or return y | ( ( p & ~y ) >> ( lg( x ) + 1 ) ) ;
}

More Related Content

Bit Hack