fix bitwise-operation bugs and optimize algorithm