# modules/number_system/negative_binary.py 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} # Using a set to ensure unique options # 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.add(random_decimal) # Add to the set to avoid duplicates options = list(options) # Convert the set to a list 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 }