This C program converts a decimal number entered by the user into its binary equivalent.
How to Use
-
Cloning from GitHub:
-
If you don't have Git installed, visit https://git-scm.com/downloads to download and install it.
-
Open a terminal window and navigate to your desired project directory.
-
Clone this repository using the following command:
git clone https://github.com/akumathedyn123/c-dec2bin-decimal-to-binary.git
This will create a new directory named
c-dec2bin-decimal-to-binaryin your current location. -
-
Compiling and Running:
-
Linux/macOS:
Open a terminal window, navigate to the project directory (
c-dec2bin-decimal-to-binary), and compile the code using a C compiler like GCC:gcc main.c -o dec2bin
This creates an executable file named
dec2bin(dec2bin.exe). Run the program by typing:./dec2bin
-
Windows:
-
Install a C compiler like MinGW (https://www.mingw-w64.org/).
-
Open a command prompt or terminal window and navigate to the project directory.
-
Compile the code using the following command (adjust the path to your MinGW compiler if necessary):
mingw32-gcc main.c -o dec2bin.exe
-
Run the program by typing:
dec2bin.exe
-
-
Usage:
The program will prompt you to enter a decimal number. After you enter the number and press Enter, it will display the equivalent binary representation.
Example:
Enter a decimal number: 15
The Binary equivalent: 1111
How the Code Works
- The
dec2binfunction takes an integernas input. - It initializes
binaryto store the binary equivalent,trackerto keep track of the place value in the binary number, andnegto check if the input is negative. - If
nis negative, it's converted to its positive absolute value usingn = -n. - A
whileloop iterates as long asnis greater than 0.- Inside the loop:
- The remainder (
n % 2) gives the last digit of the binary number. This is multiplied bytrackerand added tobinary. nis divided by 2 to remove the last digit for the next iteration.trackeris multiplied by 10 to represent the next place value in the binary number.
- The remainder (
- Inside the loop:
- If
nwas originally negative, two's complement is calculated using bitwise inversion (~binary) and adding 1 to get the correct binary representation for negative numbers. - The
mainfunction prompts the user for a decimal number, callsdec2binto convert it, and prints the result.
License:
This project is licensed under the Unlicense License. Refer to the LICENSE file for details.
Contributions
Feel free to submit pull requests for improvements or bug fixes.