The binary_basics module is designed to teach binary number systems, conversions, and arithmetic operations to computer science freshmen. The module emphasizes interactive learning through step-by-step explanations, visual representations, and guided discovery.
class BinaryTutor:
"""
Interactive binary number system tutor with difficulty-based progression.
Attributes:
difficulty_level (str): 'beginner', 'intermediate', or 'advanced'
show_prompts (bool): Enable interactive learning prompts
visual_style (str): 'simple', 'detailed', or 'colorized'
"""
def __init__(self, difficulty_level='beginner', show_prompts=True, visual_style='detailed'):
passdef decimal_to_binary(self, decimal_num: int, bit_width: int = None) -> dict:
"""
Convert decimal number to binary with educational output.
Args:
decimal_num: Integer to convert
bit_width: Optional fixed bit width (8, 16, 32)
Returns:
{
'result': '01010101',
'steps': [step objects],
'explanation': 'Full narrative explanation',
'visual': 'Visual representation with place values',
'prompts': ['Interactive questions for student']
}
"""def binary_to_decimal(self, binary_str: str) -> dict:
"""
Convert binary string to decimal with educational output.
Args:
binary_str: Binary string (e.g., '10110')
Returns:
Educational response dict (same structure as above)
"""def add_binary(self, binary1: str, binary2: str) -> dict:
"""
Perform binary addition with carry visualization.
Shows:
- Bit-by-bit addition
- Carry propagation
- Overflow detection
Returns:
Educational response with column-aligned visual
"""def subtract_binary(self, binary1: str, binary2: str, method='borrowing') -> dict:
"""
Perform binary subtraction using specified method.
Args:
method: 'borrowing' (beginner) or 'twos_complement' (advanced)
Shows:
- Bit-by-bit subtraction
- Borrow propagation OR two's complement process
"""def multiply_binary(self, binary1: str, binary2: str) -> dict:
"""
Perform binary multiplication with partial products.
Shows:
- Shift-and-add algorithm
- Partial product visualization
- Final summation
"""def to_twos_complement(self, decimal_num: int, bit_width: int = 8) -> dict:
"""
Convert signed integer to two's complement binary.
Shows:
- Why two's complement is used
- Conversion process (invert + 1)
- Range limitations for given bit width
"""def from_twos_complement(self, binary_str: str) -> dict:
"""
Interpret two's complement binary as signed decimal.
Shows:
- Sign bit identification
- Conversion process
- Positive vs negative handling
"""def bitwise_and(self, binary1: str, binary2: str) -> dict:
def bitwise_or(self, binary1: str, binary2: str) -> dict:
def bitwise_xor(self, binary1: str, binary2: str) -> dict:
def bitwise_not(self, binary: str) -> dict:def left_shift(self, binary: str, positions: int) -> dict:
"""
Perform left shift with explanation of multiplication effect.
"""
def right_shift(self, binary: str, positions: int, arithmetic=False) -> dict:
"""
Perform logical or arithmetic right shift.
Shows:
- Difference between logical and arithmetic shift
- Division effect
- Sign preservation (arithmetic)
"""def compare_binary(self, binary1: str, binary2: str) -> dict:
"""Compare two binary numbers with visual alignment."""
def validate_binary(self, binary_str: str) -> tuple[bool, str]:
"""Validate binary string format."""
def set_difficulty(self, level: str) -> None:
"""Change difficulty level dynamically."""
def get_hint(self, operation: str, context: dict) -> str:
"""Generate contextual hints for struggling students."""class ExplanationStep:
"""
Represents a single step in a calculation or conversion.
"""
step_number: int
action: str # Description of what's happening
before_state: str # State before this step
after_state: str # State after this step
reasoning: str # Why this step is performed
formula: str # Mathematical formula (if applicable)
tip: str # Learning tip or common mistake warningExample:
{
'step_number': 1,
'action': 'Divide 42 by 2',
'before_state': '42 ÷ 2',
'after_state': 'Quotient: 21, Remainder: 0',
'reasoning': 'We divide by 2 to find the next binary digit from the remainder',
'formula': '42 = 2 × 21 + 0',
'tip': 'The remainder becomes the rightmost digit'
}class EducationalResponse:
"""
Standard return format for all educational methods.
"""
result: Any # The actual answer
result_decimal: int # Decimal equivalent (if applicable)
steps: List[ExplanationStep] # Step-by-step process
explanation: str # Full narrative explanation
visual: str # ASCII visual representation
prompts: List[str] # Interactive questions (if enabled)
hints: List[str] # Available hints
difficulty: str # Difficulty level used
concepts: List[str] # CS concepts covered
common_mistakes: List[str] # Common errors to avoidclass BinaryVisual:
"""
Structure for creating aligned visual representations.
"""
binary_string: str
place_values: List[int] # [128, 64, 32, 16, 8, 4, 2, 1]
bit_positions: List[int] # [7, 6, 5, 4, 3, 2, 1, 0]
decimal_contributions: List[int] # Actual values per bit
annotations: Dict[str, str] # Additional labelsBinary: 1011
Decimal: 11
Breakdown:
1×8 + 0×4 + 1×2 + 1×1 = 11
Binary Representation of 11
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Position: 7 6 5 4 3 2 1 0
─────────────────────────────
Bit: 0 0 0 0 1 0 1 1
─────────────────────────────
Value: 128 64 32 16 8 4 2 1
─────────────────────────────
Result: 0 0 0 0 8 0 2 1
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Sum: 0 + 0 + 0 + 0 + 8 + 0 + 2 + 1 = 11
Uses ANSI color codes to highlight:
- Active bits (green)
- Zero bits (dim gray)
- Carry bits (yellow)
- Result bits (cyan)
Carry: 1 1 0 0 (carry bits shown above)
─────────
A: 1 0 1 1
B: + 0 1 1 0
─────────
Result: 1 0 0 0 1
─────────
Step-by-step:
Column 0: 1 + 0 = 1, carry 0
Column 1: 1 + 1 = 0, carry 1
Column 2: 0 + 1 + carry(1) = 0, carry 1
Column 3: 1 + 0 + carry(1) = 0, carry 1
Column 4: carry(1) = 1
Converting -5 to 8-bit two's complement:
Step 1: Convert positive value to binary
5 in binary: 0000 0101
Step 2: Invert all bits (one's complement)
Inverted: 1111 1010
↑↑↑↑ ↑↑↑↑
All bits flipped
Step 3: Add 1
Inverted: 1111 1010
Add 1: + 1
─────────
Result: 1111 1011
This is -5 in two's complement!
class PromptSystem:
"""
Manages interactive learning prompts based on Socratic method.
"""
def generate_prompt(self, operation: str, inputs: dict, difficulty: str) -> str:
"""
Generate a leading question before showing solution.
Example for decimal_to_binary(42):
- Beginner: "What do you get when you divide 42 by 2? What's the remainder?"
- Intermediate: "How many times does 32 (2^5) fit into 42?"
- Advanced: "What's the most significant bit position needed for 42?"
"""
def generate_checkpoint_question(self, step_number: int, context: dict) -> str:
"""
Generate questions at key points during calculation.
Example during binary addition at carry step:
"We have a carry from the previous column. What happens when we add 1+1+1?"
"""class HintSystem:
"""
Provides progressive hints without giving away the answer.
"""
hint_levels = {
1: "Conceptual hint - reminds of relevant concept",
2: "Strategic hint - suggests approach",
3: "Tactical hint - shows similar example",
4: "Detailed hint - reveals first step",
5: "Final hint - shows complete solution"
}
def get_hint(self, operation: str, current_step: int, level: int = 1) -> str:
"""Return appropriate hint based on level."""Problem: Convert 42 to binary
-
Level 1 (Conceptual): "Remember, binary uses powers of 2. What's the largest power of 2 that fits in 42?"
-
Level 2 (Strategic): "Try the division-by-2 method. Keep dividing and track remainders."
-
Level 3 (Tactical): "Let's try a smaller number first: Convert 10 to binary using division."
-
Level 4 (Detailed): "First step: 42 ÷ 2 = 21 remainder 0. The remainder is your first bit."
-
Level 5 (Complete): Shows full step-by-step solution.
class AdaptiveLearning:
"""
Tracks student performance and adjusts difficulty.
"""
def analyze_performance(self, history: List[dict]) -> dict:
"""
Analyze recent attempts to suggest difficulty adjustment.
Returns:
{
'accuracy': float,
'speed': float,
'common_errors': List[str],
'suggested_level': str,
'ready_for_next': bool
}
"""
def suggest_next_exercise(self, current_skill: dict) -> dict:
"""Recommend next practice problem."""# binary_basics.py depends on:
from typing import List, Dict, Tuple, Optional, Any
import math
from dataclasses import dataclass
from enum import Enum
# Future integration points:
# - hexadecimal_converter (for hex<->binary conversions)
# - floating_point_basics (for IEEE 754 representation)
# - logic_gates (for understanding bitwise operations)
# - assembly_basics (for register operations)# Public API for other modules
__all__ = [
'BinaryTutor', # Main class
'EducationalResponse', # Response structure
'DifficultyLevel', # Enum for difficulty
'quick_convert', # Convenience function
'batch_operations', # For automated exercises
]# assessment_module.py can import:
from binary_basics import BinaryTutor, DifficultyLevel
def generate_quiz(difficulty: str, num_questions: int):
tutor = BinaryTutor(difficulty, show_prompts=False)
# Generate questions using tutor's methods# visualization_module.py can import:
from binary_basics import BinaryVisual
def create_interactive_diagram(binary_num: str):
visual = BinaryVisual(binary_num)
# Create web-based interactive visualization# practice_module.py can import:
from binary_basics import BinaryTutor, AdaptiveLearning
def adaptive_practice_session(student_id: str):
tutor = BinaryTutor(difficulty='beginner')
adaptive = AdaptiveLearning()
# Provide personalized practiceAll modules exchange data using JSON-serializable dictionaries:
# Standard format for cross-module communication
{
'operation': 'decimal_to_binary',
'inputs': {'decimal_num': 42, 'bit_width': 8},
'output': {
'result': '00101010',
'decimal_equivalent': 42,
'metadata': {...}
},
'timestamp': '2025-10-15T10:30:00Z',
'student_id': 'optional',
'difficulty': 'beginner'
}class BinaryTutorEvents:
"""
Event hooks for integration with LMS or analytics systems.
"""
on_exercise_start: callable
on_exercise_complete: callable
on_hint_requested: callable
on_error_made: callable
on_difficulty_change: callable
def emit_event(self, event_type: str, data: dict):
"""Emit event for external systems to consume."""BinaryTutorclass with basic initializationdecimal_to_binary()andbinary_to_decimal()with simple explanations- Basic
EducationalResponsestructure - Simple visual representations
add_binary()with carry visualizationsubtract_binary()(borrowing method)- Basic bitwise operations (AND, OR, XOR, NOT)
- Two's complement methods
- Shift operations
- Advanced visual representations
- Interactive prompt system
- Hint progression system
- Adaptive difficulty
- Performance tracking
- Comprehensive test suite
-
Conversion Accuracy Tests
- Verify mathematical correctness
- Edge cases (0, negative numbers, large numbers)
- Bit width handling
-
Explanation Quality Tests
- Verify all steps are present
- Check visual formatting
- Validate educational completeness
-
Difficulty Level Tests
- Beginner outputs simplified content
- Advanced includes complex explanations
- Appropriate method availability
-
Integration Tests
- Mock external module interactions
- Verify data format compatibility
-
User Experience Tests
- Interactive prompts work correctly
- Hints are helpful and progressive
- Visual representations are clear
# Test cases covering key scenarios
test_cases = {
'simple_positive': [1, 5, 15, 42, 127],
'powers_of_two': [1, 2, 4, 8, 16, 32, 64, 128],
'edge_cases': [0, -1, -128, 255],
'large_numbers': [1000, 4095, 65535],
}tutor = BinaryTutor(difficulty='beginner', show_prompts=True)
result = tutor.decimal_to_binary(42)
print(result['visual'])
# Shows simple breakdown
for step in result['steps']:
print(f"{step.action}: {step.reasoning}")
for prompt in result['prompts']:
print(f"Q: {prompt}")
# Student attempts to answer before seeing next steptutor = BinaryTutor(difficulty='intermediate', show_prompts=False)
practice_problems = [13, 27, 51, 99]
for num in practice_problems:
result = tutor.decimal_to_binary(num)
# Student solves first, then checks result
print(f"Answer: {result['result']}")
print(f"Check your work:\n{result['explanation']}")tutor = BinaryTutor(difficulty='advanced')
# Two's complement
result = tutor.to_twos_complement(-42, bit_width=8)
print(result['visual'])
# Shows full conversion process with sign bit explanation
# Binary arithmetic
result = tutor.add_binary('10110', '01101')
print(result['visual'])
# Shows column-by-column addition with carry propagation-
Web Interface Integration
- REST API for educational responses
- WebSocket for real-time tutoring
- Integration with online learning platforms
-
Gamification
- Achievement system for mastering concepts
- Timed challenges with leaderboards
- Progress badges and certificates
-
Advanced Topics
- Floating-point representation (IEEE 754)
- Binary-coded decimal (BCD)
- Gray code
- Error detection and correction codes
-
Multilingual Support
- Internationalization of explanations
- Language-specific educational approaches
-
Accessibility Features
- Screen reader optimization
- Braille-friendly representations
- Adjustable visual contrast
- Machine learning for personalized learning paths
- Natural language processing for student question answering
- Automated difficulty calibration based on student cohort data
- Quick Start Guide: 5-minute introduction to using the module
- Concept Explanations: Why binary matters in computing
- Tutorial Series: Progressive lessons from basic to advanced
- FAQ: Common questions and misconceptions
- Pedagogical Guide: How to integrate into curriculum
- Assessment Tools: How to use for evaluation
- Customization Guide: Adapting difficulty and content
- Analytics Guide: Interpreting student performance data
- API Reference: Complete method documentation
- Architecture Guide: This document
- Contributing Guide: How to extend the module
- Testing Guide: How to validate changes
- Student comprehension improvement (pre/post testing)
- Time to mastery reduction
- Error rate reduction over time
- Student satisfaction scores
- Code coverage > 90%
- All operations mathematically verified
- Response time < 100ms for typical operations
- Clear, maintainable code structure
- Students can use without external help
- Visual representations are immediately understandable
- Explanations match freshman comprehension level
- Hint system successfully guides without solving
Version: 1.0 Date: 2025-10-15 Author: Core Architect Status: Ready for Implementation
This architecture provides a complete foundation for building an educational binary number system module that scales from beginner to advanced learners while maintaining strong pedagogical principles and clean software architecture.