File size: 1,264 Bytes
d924141
 
32f2e18
 
 
d924141
32f2e18
 
 
 
d924141
32f2e18
d924141
32f2e18
 
d924141
 
 
 
32f2e18
d924141
 
 
 
 
32f2e18
d924141
32f2e18
 
 
d924141
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import random

title = "2's Complement"
description = "This module covers the representation of numbers using the 2's complement method, which is commonly used for representing negative numbers in binary."

def generate_question():
    num = random.randint(-8, 7)
    bit_length = 4
    if num >= 0:
        binary = bin(num)[2:].zfill(bit_length)
    else:
        binary = bin((1 << bit_length) + num)[2:]
    
    question = f"What is the 2's complement representation of {num}?"
    correct_answer = binary
    options = [correct_answer]
    
    # Generate incorrect options
    while len(options) < 5:
        fake_option = bin(random.randint(-8, 7) & 0xF)[2:]
        if fake_option not in options:
            options.append(fake_option)
    
    random.shuffle(options)
    explanation = (
        f"The 2's complement representation of {num} is {binary}."
        "\n\n**Step-by-step solution:**\n"
        "1. If the number is positive, convert it to binary and pad with leading zeros to fit the bit length.\n"
        "2. If the number is negative, take its absolute value, convert to binary, invert the digits, and add 1.\n"
        "3. The result is the 2's complement representation."
    )
    return question, options, correct_answer, explanation