Comprehensive Explanation - Clearing Upper 4 Bits and String Case Conversion With 'AND'
Comprehensive Explanation - Clearing Upper 4 Bits and String Case Conversion With 'AND'
2. Theory:
The AND instruction is a bitwise operation where each bit in the
destination is logically ANDed with the corresponding bit in the source
operand. Mathematically:
3. Steps:
o Load Initial Value: Place an 8-bit value into a register (e.g., AL).
o Result: The upper 4 bits are cleared, and the lower 4 bits remain
unchanged.
4. Example Code:
5. Explanation of Result:
Initially: AL=0 b 11011011
Mask: 0 b 00001111
2. Theory:
o ASCII Properties:
Lowercase letters (a to z ) have ASCII values {97 , 98 , … ,122 },
represented in binary as 0 b 011 xxxxx .
Uppercase letters ( A to Z ) have ASCII values {65 ,66 , … , 90 },
represented as 0 b 010 xxxxx .
o Key Insight:
o Mask Design:
3. Steps:
o Load the String: Use a pointer register (ESI) to traverse the
string and a counter (ECX) for the loop.
4. Example Code:
section .data
mystring db 'hello, world!', 0 ; Null-terminated string
section .text
global _start
_start:
mov ecx, 13 ; String length
mov esi, mystring ; String address
L1:
and BYTE [esi], 0b11011111 ; Clear bit 5
inc esi ; Move to the next character
loop L1 ; Repeat for all characters
5. Explanation of Result:
Initial string: 'hello, world!'
ASCII values: {104 ,101 , 108 , 108 ,111 , 44 , 32 ,119 ,111 , 114 ,108 , 100 , 33}
After clearing bit 5: {72 , 69 , 76 ,76 ,79 , 44 ,32 , 87 , 79 , 82, 76 , 68 , 33 },
which corresponds to 'HELLO, WORLD!'.
section .text
global _start
_start:
; Clearing upper 4 bits
mov al, 0xAD ; Load AL with 0xAD
and al, 0x0F ; Clear upper 4 bits
; AL = 0x0D
Expected Outputs:
1. AL=0 x 0 D after clearing upper 4 bits.
2. Transformed string: "GOODBYE!".
2. Practical:
o Write code to reverse the transformation (uppercase to
lowercase).
3. Optimization:
Note: Both operands must be of the same size (e.g., 8, 16, 32, or 64 bits).
Step-by-Step Execution
Initial Values:
o Mask: 00001111.
AL: 11011011
Mask: 00001111
-----------------
Result:00001011
Result:
Conversion Logic
To convert a lowercase ASCII character to uppercase:
1. Mask: Use the AND operation with a mask of 11011111 (0xDF in
hexadecimal).
2. Effect: Clears bit 5, leaving other bits unchanged.
Example: Converting a String to Uppercase
Problem Statement: Convert a null-terminated string of lowercase ASCII
characters into uppercase.
Assembly Code
mov ecx, LENGTHOF mystring ; Load string length into ECX
mov esi, OFFSET mystring ; Load string starting address into ESI
L1: and BYTE PTR [esi], 11011111b ; Clear bit 5 of current character
inc esi ; Move to the next character
loop L1 ; Repeat for all characters
Detailed Explanation
1. Initialization:
2. Bitwise Operation:
o Perform AND with 11011111b for each byte.
3. Iteration:
2. Clearing Flags:
4. Bitfield Manipulation: