Skip to content

CLI tool that converts decimal numbers (including fractions) to binary using recursive algorithms. Built with Node.js to practice recursion and number system conversion. 🔢

Notifications You must be signed in to change notification settings

rishiverma12031/binary-converter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 

Repository files navigation

Binary Converter 🔢

A command-line tool that converts decimal numbers (including fractions) to binary representation. Built with Node.js using recursion and implementing proper mathematical conversion algorithms.

Node.js JavaScript CLI Math

📖 About The Project

This CLI application converts decimal numbers to binary format using mathematical algorithms implemented through recursive functions. It handles both integers and fractional decimal numbers, demonstrating core programming concepts like recursion, input validation, and number system conversion.

What Makes This Special

  • Handles Integers AND Fractions - Not just whole numbers
  • Pure Recursion - Mathematical algorithms implemented recursively
  • Input Validation - Checks for valid decimal numbers
  • Educational - Clean code demonstrating recursion concepts

🎯 Features

  • 🔄 Recursive Conversion - Uses mathematical recursion for both integer and fractional parts
  • 🔢 Decimal to Binary - Accurate conversion of decimal numbers
  • 💯 Fraction Support - Converts decimal fractions (e.g., 5.75 → 101.11)
  • Input Validation - Prevents invalid inputs (negative numbers, non-numbers, empty strings)
  • 🎨 Clean CLI Interface - Simple and straightforward user experience
  • 📚 Educational Code - Clear implementation of conversion algorithms

📸 Demo

$ node app.mjs

Enter the number: 10
You have entered 10
The binary equivalent of 10 is: 1010

$ node app.mjs

Enter the number: 5.75
You have entered 5.75
The binary equivalent of 5.75 is: 101.11

$ node app.mjs

Enter the number: -5
Please input a decimal number greater than 0
Enter the number: 12.5
You have entered 12.5
The binary equivalent of 12.5 is: 1100.1

🧮 How Binary Conversion Works

Integer Conversion

The algorithm divides the number by 2 repeatedly and keeps track of remainders:

Example: 10 (decimal) → 1010 (binary)
10 ÷ 2 = 5 remainder 0
5 ÷ 2 = 2 remainder 1
2 ÷ 2 = 1 remainder 0
1 ÷ 2 = 0 remainder 1
Reading remainders from bottom to top: 1010

Fraction Conversion

The algorithm multiplies the fraction by 2 repeatedly and tracks the integer part:

Example: 0.75 (decimal) → 0.11 (binary)
0.75 × 2 = 1.5 → integer part: 1, fraction: 0.5
0.5 × 2 = 1.0 → integer part: 1, fraction: 0.0
Reading integer parts: 0.11

🛠️ Built With

  • Node.js - JavaScript runtime
  • ES6 Modules (.mjs) - Modern JavaScript syntax
  • prompt-sync - User input handling
  • Recursion - Core algorithm implementation

📋 Prerequisites

  • Node.js (v12.0.0 or higher)
  • npm (Node Package Manager)

Check your installation:

node --version
npm --version

🚀 Installation & Setup

1. Clone the Repository

git clone https://github.com/rishiverma12031/BinaryConverter.git
cd BinaryConverter

2. Install Dependencies

npm install prompt-sync

3. Run the Converter

node app.mjs

💻 Usage

  1. Run the application: node app.mjs
  2. Enter a decimal number when prompted (positive numbers only)
  3. View the binary result displayed in the terminal

Valid Inputs

  • Whole numbers: 10, 255, 1024
  • Decimal fractions: 5.5, 12.75, 0.625
  • Zero: 0

Invalid Inputs (Will prompt for re-entry)

  • Negative numbers: -5
  • Non-numeric values: abc, 12a
  • Empty input:

📁 Project Structure

BinaryConverter/
│
├── app.mjs              # Main application file
├── package.json         # Project dependencies (create this)
└── README.md           # Documentation

🔧 Code Structure

Main Functions

convertToBinary(decimalNum)

  • Main conversion function
  • Splits number into integer and fractional parts
  • Combines binary results from both parts

convertToBinaryInteger(decimalNum)

  • Recursive function for converting integer part
  • Base case: Returns when number is 0 or 1
  • Recursive case: Divides by 2 and processes remainder

convertToBinaryFraction(decimalNum)

  • Recursive function for converting fractional part
  • Base case: Returns when fraction becomes 0
  • Recursive case: Multiplies by 2 and tracks integer part

checkInputValue()

  • Validates user input
  • Checks for negative numbers, NaN, and empty strings
  • Recursive - Re-prompts on invalid input

🎓 Learning Outcomes

This project demonstrates understanding of:

Core Concepts

  • Recursion - Multiple recursive functions with proper base cases
  • Number Systems - Understanding binary and decimal conversion
  • Mathematical Algorithms - Implementing standard conversion methods
  • Type Coercion - String/Number conversions and type handling
  • Input Validation - Using isNaN(), comparison operators
  • String Manipulation - split(), String() conversions
  • ES6 Modules - Modern import/export syntax

Programming Practices

  • Clean function separation
  • Recursive algorithm design
  • Error handling and validation
  • User-friendly CLI interface

🧪 Test Cases

Try these inputs to test the converter:

Decimal Expected Binary Description
0 0 Zero
1 1 One
10 1010 Simple integer
255 11111111 8-bit max value
0.5 0.1 Simple fraction
0.75 0.11 Three-quarters
5.75 101.11 Mixed number
12.5 1100.1 Decimal with .5

🔬 Algorithm Explanation

Integer Part (Division Method)

function convertToBinaryInteger(decimalNum) {
    // Base case: 0 or 1 can't be divided further
    if (decimalNum === 0 || decimalNum === 1) return String(decimalNum);
    
    // Recursive case: divide by 2 and concatenate remainder
    return convertToBinaryInteger(Math.floor(decimalNum / 2)) + String(decimalNum % 2);
}

How it works:

  1. Divide number by 2 using Math.floor() for integer division
  2. Get remainder using modulo operator %
  3. Recursively process quotient
  4. Concatenate remainders in reverse order

Fractional Part (Multiplication Method)

function convertToBinaryFraction(decimalNum) {
    // Base case: fraction becomes 0
    if(decimalNum === 0) return String(decimalNum);
    
    // Recursive case: multiply by 2 and track integer part
    return String(Math.floor(decimalNum * 2)) + 
           convertToBinaryFraction(decimalNum * 2 - Math.floor(decimalNum * 2));
}

How it works:

  1. Multiply fraction by 2
  2. Extract integer part (0 or 1) using Math.floor()
  3. Get new fraction part (remainder after extracting integer)
  4. Recursively process new fraction
  5. Concatenate results in order

🎨 Customization Ideas

Easy Modifications

  • Add support for other number bases (octal, hexadecimal)
  • Display step-by-step conversion process
  • Add option to convert binary back to decimal
  • Implement iterative versions alongside recursive

Medium Challenges

  • Add command-line arguments for batch conversion
  • Output conversion steps for educational purposes
  • Support multiple number formats as input
  • Add file input/output for bulk conversions

Advanced Features

  • Create a GUI version with Electron
  • Add support for negative numbers (two's complement)
  • Implement scientific notation support
  • Build a web version with conversion visualization

🐛 Troubleshooting

Common Issues

Error: "Cannot find module 'prompt-sync'"

npm install prompt-sync

Error: "SyntaxError: Cannot use import statement outside a module"

  • Ensure file extension is .mjs, OR
  • Add "type": "module" to package.json

Infinite loop with fractions

  • This occurs with repeating binary fractions (like 0.1 decimal)
  • Consider adding a precision limit in production code

Input validation not working

  • Check that isNaN() is used correctly
  • Ensure comparison operators are appropriate (< for negative check)

🌟 Future Enhancements

  • Add precision control for fractional conversions
  • Implement reverse conversion (binary to decimal)
  • Support for other number systems (octal, hex)
  • Add step-by-step explanation mode
  • Create batch conversion from file
  • Build interactive web interface
  • Add negative number support (two's complement)
  • Include scientific notation handling
  • Add unit tests
  • Implement conversion history

🤝 Contributing

Contributions are welcome! Here's how:

  1. Fork the project
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

📝 License

This project is open source and available under the MIT License.

👤 Author

Rishi Verma

🙏 Acknowledgments

  • Built to learn and practice recursion and mathematical algorithms
  • Implements standard decimal-to-binary conversion methods
  • Uses prompt-sync for user input

📚 Resources & References

💡 Educational Note

While JavaScript provides Number.toString(2) for binary conversion, this project implements the algorithm from scratch using recursion to demonstrate:

  • How recursion solves mathematical problems
  • Understanding of number system conversion
  • Implementation of standard conversion algorithms
  • Practical application of recursive thinking

Ready to convert? Run node app.mjs and start converting! 🔢

Built with ❤️ while learning recursion and mathematical algorithms in JavaScript

About

CLI tool that converts decimal numbers (including fractions) to binary using recursive algorithms. Built with Node.js to practice recursion and number system conversion. 🔢

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published