Chapter 11 - Bitwise Instructions

11
.1  Bitwise

Bitwise operators work at the binary level.  They allow you to manipulate individual bits within an integer.  They are used for low-level programming of device drivers, graphics, and communications protocols.  C++ and Java also have the bitwise operators.  Bitwise operations would allow you to implement a large number of Boolean variables without using much space.  A 32-bit integer couple be used for 32 Boolean variables.

Here is an online bitwise calculator to help visualize:
http://bitwisecmd.com/

 Bitwise Operators Name C++/Java Operator Example x86 Example - Results placed in first operand Bitwise AND & 42  00101010 & 27  00011011 = 10  00001010 mov eax, 42 and eax, 27 Bitwise OR | 3  00000011 & 17  00010001 = 19  00010011 mov [A], 3 or [A], 17 Bitwise XOR ^ 3  00000011 ~ 17  00010001 = 18  00010010 mov eax, 3 mov ebx, 17 xor al, bl Bitwise NOT ~ ~ 42  00101010 = 213 11010101 mov edx, 42 not edx Shift Left << 42 << 1  00101010 = 84     01010100 mov eax, 42 shl eax, 1 Shift Right >> 100 >> 2  01100100 = 25      00011001 mov [A], 100 shr [A], 2

The AND is a good way to isolate bits.  If you AND binary 10101001 with 00001111 you will get the right 4 digits: 00001001.

The shift left is a fast way to multiply and integer by 2.  The shift right is a fast way to divided an integer by 2.  If bits slide off the end, the carry flag is set.  You shouldn't use the shift left and right for negative numbers.

 bitwise.asm ```format PE console include 'win32ax.inc' ;======================================= section '.code' code readable executable ;======================================= start: mov eax, 42 and eax, 27 mov [A], eax cinvoke printf,"42 & 27 = %d %c",[A],10 mov [A], 3 or [A], 17 cinvoke printf,"3 | 17 = %d %c",[A],10 mov eax, 3 mov ebx, 17 xor al, bl mov [A], eax cinvoke printf,"3 ^ 17 = %d %c",[A],10 mov [A], 100 shr [A], 2 cinvoke printf,"100 >> 2 = %d %c",[A],10 invoke Sleep,-1 ;====================================== section '.data' data readable writeable ;====================================== A dd 0 ;==================================== section '.idata' import data readable ;==================================== library msvcrt,'msvcrt.dll',kernel32,'kernel32.dll' import msvcrt,printf,'printf' import kernel32,Sleep,'Sleep' ``` Output 42 & 27 = 10 3 | 17 = 19 3 ^ 17 = 18 100 >> 2 = 25