cntlzw
Count Leading Zeros Word - 7C 00 00 34
cntlzw
Instruction Syntax
Mnemonic | Format | Flags |
cntlzw | rA,rS | Rc = 0 |
cntlzw. | rA,rS | Rc = 1 |
Instruction Encoding
0
1
1
1
1
1
S
S
S
S
S
A
A
A
A
A
0
0
0
0
0
0
0
0
0
0
1
1
0
1
0
Rc
Field | Bits | Description |
Primary Opcode | 0-5 | 011111 (0x1F) |
rS | 6-10 | Source register S |
rA | 11-15 | Destination register A |
Reserved | 16-20 | 00000 |
Reserved | 21 | 0 |
XO | 22-30 | 000011010 (26) |
Rc | 31 | Record Condition Register |
Operation
n ← 0 do while (n < 32) if rS[n] = 1 then leave n ← n + 1 rA ← n
The count leading zeros word instruction counts the number of consecutive zero bits starting from the most significant bit (bit 0) of register rS and places this count in register rA. The count can range from 0 (if bit 0 is 1) to 32 (if rS contains all zeros).
Affected Registers
Condition Register (CR0 field)
(if Rc = 1)
- LT (Less Than)
- GT (Greater Than)
- EQ (Equal)
- SO (Summary Overflow)
For more information on condition codes see Section 2.1.3, "Condition Register," in the PowerPC Microprocessor Family: The Programming Environments manual.
Examples
Basic Count Leading Zeros
li r3, 0x12345678 # Load test value cntlzw r4, r3 # Count leading zeros: r4 = 3 (bits 0,1,2 are zero) li r5, 0x80000000 # Load value with MSB set cntlzw r6, r5 # Count leading zeros: r6 = 0 (MSB is set) li r7, 0x00000000 # Load all zeros cntlzw r8, r7 # Count leading zeros: r8 = 32 (all zeros)
Find First Set Bit Position
# Find the position of the most significant bit set lwz r3, data_value(r0) # Load data value cntlzw r4, r3 # Count leading zeros subfic r5, r4, 31 # r5 = 31 - leading_zeros = MSB position
Power of Two Check
# Check if value is a power of 2 lwz r3, input_value(r0) # Load input subic r4, r3, 1 # r4 = r3 - 1 and r5, r3, r4 # r5 = r3 & (r3-1) cntlzw. r6, r5 # Count leading zeros and set CR0 # If r6 = 32 (EQ set), then r3 is power of 2
Bit Manipulation Utilities
# Find highest bit position cntlzw r4, r3 # Count leading zeros subfic r5, r4, 31 # Convert to bit position # Calculate log2 for powers of 2 cntlzw r4, r3 # Count leading zeros subfic r5, r4, 31 # r5 = log2(r3) for power of 2
Normalize Value
# Shift value to normalize (make MSB = 1) cntlzw r4, r3 # Count leading zeros slw r5, r3, r4 # Shift left by leading zero count # r5 now has MSB = 1 (normalized)
Fast Division by Powers of 2
# Divide by finding the highest bit and using shifts cntlzw r4, r3 # Count leading zeros subfic r5, r4, 31 # Get MSB position srw r6, r3, r5 # Right shift to divide