File size: 2,451 Bytes
3540df9
d924141
c9ca893
 
32f2e18
d924141
3540df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9ca893
 
3540df9
 
 
d924141
 
c9ca893
3540df9
 
 
 
 
 
 
 
c9ca893
 
 
 
3540df9
c9ca893
 
 
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import random

title = "Negative Binary Numbers"
description = "This module covers negative binary numbers and their representation."

def generate_question():
    bit_lengths = [2, 3, 4, 5, 6, 7, 8]
    num_bits = random.choice(bit_lengths)
    
    def generate_binary_number(length):
        return ''.join(random.choice('01') for _ in range(length))
    
    number = generate_binary_number(num_bits)
    
    def calculate_negative_binary(binary_str):
        # Interpret the binary string as a signed number
        if binary_str[0] == '1':
            # Two's complement
            ones_complement = ''.join('1' if bit == '0' else '0' for bit in binary_str)
            twos_complement = bin(int(ones_complement, 2) + 1)[2:].zfill(len(binary_str))
            decimal_value = -int(twos_complement, 2)
        else:
            decimal_value = int(binary_str, 2)
        
        return decimal_value
    
    def decimal_to_binary(value, length):
        # Convert a decimal number to binary with a given length
        if value < 0:
            value = (1 << length) + value
        return bin(value)[2:].zfill(length)
    
    correct_decimal = calculate_negative_binary(number)
    correct_binary = decimal_to_binary(correct_decimal, num_bits)
    
    options = [correct_decimal]
    
    # Generate incorrect answers
    while len(options) < 4:
        random_decimal = random.randint(-2**(num_bits-1), 2**(num_bits-1)-1)
        if random_decimal != correct_decimal:
            options.append(random_decimal)
    
    random.shuffle(options)
    
    question = f"What is the decimal value of the signed {num_bits}-bit binary number {number}?"
    explanation = f"The decimal value of the signed {num_bits}-bit binary number {number} is {correct_decimal}."
    step_by_step_solution = [
        f"Step 1: Identify if the binary number is positive or negative. The leftmost bit indicates the sign.",
        f"Step 2: If the leftmost bit is '1', calculate the two's complement to find the magnitude of the negative number.",
        f"Step 3: Convert the binary number to decimal considering its sign.",
        f"Step 4: The decimal value of the signed {num_bits}-bit binary number {number} is {correct_decimal}."
    ]
    
    return {
        "question": question,
        "options": options,
        "correct_answer": correct_decimal,
        "explanation": explanation,
        "step_by_step_solution": step_by_step_solution
    }