|
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] |
|
|
|
|
|
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 |
|
|