|
|
|
|
|
import random |
|
import sympy as sp |
|
|
|
title = "2's Complement Questions" |
|
description = "This module explains the 2's complement method for representing negative numbers." |
|
|
|
def generate_question(): |
|
bit_lengths = [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_twos_complement(binary_str, length): |
|
if binary_str == '0' * length: |
|
return binary_str |
|
|
|
ones_complement = ''.join('1' if bit == '0' else '0' for bit in binary_str) |
|
|
|
twos_complement = bin(int(ones_complement, 2) + 1)[2:] |
|
|
|
return twos_complement.zfill(length)[-length:] |
|
|
|
correct_answer = calculate_twos_complement(number, num_bits) |
|
|
|
options = {correct_answer} |
|
|
|
|
|
while len(options) < 4: |
|
invalid_number = generate_binary_number(num_bits) |
|
invalid_twos_complement = calculate_twos_complement(invalid_number, num_bits) |
|
if invalid_twos_complement != correct_answer: |
|
options.add(invalid_twos_complement) |
|
|
|
options = list(options) |
|
random.shuffle(options) |
|
|
|
question = f"What is the 2's complement of the {num_bits}-bit binary number {number}?" |
|
explanation = f"The 2's complement of the {num_bits}-bit binary number {number} is {correct_answer}." |
|
step_by_step_solution = [ |
|
f"Step 1: Invert the bits (1's complement) of the binary number {number}.", |
|
f"Step 2: Add 1 to the result to get the 2's complement.", |
|
f"Step 3: Ensure the result is a {num_bits}-bit binary number by truncating or zero-padding if necessary.", |
|
f"Step 4: The 2's complement of the {num_bits}-bit binary number {number} is {correct_answer}." |
|
] |
|
|
|
return { |
|
"question": question, |
|
"options": options, |
|
"correct_answer": correct_answer, |
|
"explanation": explanation, |
|
"step_by_step_solution": step_by_step_solution |
|
} |
|
|