Extract bit fields

Every instruction decoder cuts fields out of a word with a shift and a mask. Do it for any field.

What to build

A program that reads a hexadecimal word and prints the value of several bit fields.

Requirements

  • A field is written as hi lo: the bits from bit number hi (higher) down to bit number lo, where bit 0 is the least significant bit.
  • Print the value of each field as a decimal number, one per line, in the order asked.

Input

A line with the word as hex digits (no prefix), a line with q, then q lines, each hi lo.

Output

q lines.

Constraints

The word has at most 8 hex digits; 1 ≤ q ≤ 20; 0 ≤ lo ≤ hi ≤ 31.

Example

Input:

3A57
3
15 12
11 8
3 0

Output:

3
10
7

Why it works

Shifting right by lo drops the bits below the field, so the field now starts at bit 0. The mask of (hi − lo + 1) ones then clears everything above it.

Examples

Example 1 · Input
3A57
3
15 12
11 8
3 0
Expected output
3
10
7
Example 2 · Input
FF
2
7 0
3 3
Expected output
255
1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

To read bits hi down to lo: shift right by lo, then AND with a mask of (hi - lo + 1) ones.

Hint 2

The mask is (1 << (hi - lo + 1)) - 1.

Solution

Show one correct solution (try it yourself first)
word = int(input().strip(), 16)
q = int(input())
for _ in range(q):
    hi, lo = map(int, input().split())
    print((word >> lo) & ((1 << (hi - lo + 1)) - 1))

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Instruction sets and addressing modes →