CET 3510 Lecture 11 Bit Manipulation in a
CET 3510 – Lecture 11 Bit Manipulation in a High-Level Programming Language Dr. José M. Reyes Álamo
Bitwise Operations �A logical operation that is performed between bit of the operand(s) in their corresponding position ◦ ◦ Bitwise AND OR NOT XOR
Bitwise Operations � Recipe: 1. Move the first operand into an appropriate register 2. Perform the corresponding operation proving the first and second operand � HLA Code Example: ◦ mov( eax, ecx ); ◦ and( ebx, ecx ); ◦ mov( eax, ecx ); ◦ or( ebx, ecx ); ◦ mov( eax, ecx ); ◦ xor( ebx, ecx ); ◦ mov( ebx, ecx ); ◦ not( ecx ); //BE CAREFUL
Bitwise Operations in C/C++ � Result ◦ ◦ is the same, syntax is different Bitwise � Be AND operator: & OR operator: | NOT operator: ~ XOR operator: ^ careful: ◦ Do not confuse these with the logical comparison operators: &&, ||, !
Bitwise Operations in C/C++ �Code Example: void logical. Operations(){ } int x, y, z; x = 5; y = 2; z = x & y; cout << "x & y = " z = x | y; cout << "x | y = " z = x ^ y; cout << "x ^ y = " z = ~x; cout << "~x = " << system("PAUSE"); << z << endl;
Shifting Left in HLA � Shift left move each bit n positions to the ◦ Lower order bits becomes a 0 ◦ Higher order bit become a carry out ◦ HLA code: �shl( count, dest ) | count = positions to shift; dest = register or variable ◦ Shifting n places to the left one position is equivalent to multiplying by the base (radix) n times (radix)
Shifting Right in HLA � Shift right move each bit n positions to the ◦ Higher order bits becomes a 0 ◦ Lower order bit become a carry out ◦ HLA code: �shr( count, dest ) | count = positions to shift; dest = register or variable �sar( count, dest ) | count = positions to shift; dest = register or variable. Used for arithmetic shifting. n places to the right one position is equivalent to dividing by the base (radix) n � Shifting times
Shifting in C/C++ � The bitwise shifting operators are ◦ Right shift (>>) ◦ Left shift (<<) � Be careful with the compiler as shifting (especially shifting right) might return unexpected results
Shifting in C++ � Code Example: void shifting. Operations(){ int x, y, z; x = 2; x = x << 5; cout << "x shifted left = " << x << endl; x = x >> 1; cout << "x shifted right = " << x << endl; }
Bit Manipulation Example HLA � HLA Code: stdout. put( “Enter the current month, day, and year: “ ); stdin. get( month, day, year ); mov( 0, ax ); mov( ax, packed. Date ); //Just in case there is an error. mov( month, al ); shl( 5, ax ); or( day, al ); shl( 7, ax ); or( year, al ); mov( ax, packed. Date ); stdout. put( “Packed data = $”, packed. Date, nl );
Bit Manipulation Example C++ void packed. Date(){ int month, day, year, packed. Date; cout << "Enter the current month, day, and year: " << endl; cin >> month >> day >> year; packed. Date } = = = 0; packed. Date | month; << 5; | day; << 7; | year; cout << "Packed date is " << hex << packed. Date << endl;
- Slides: 11