Created
September 28, 2023 18:21
-
-
Save Dynesshely/ad428abf48edba512b02c60705aa426e to your computer and use it in GitHub Desktop.
Convert a decimal number into a binary number in C-Lang, including a handmade stack implement.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
// Declare an array to emulate a stack | |
// Opacity of this stack is 10000 | |
// `stack_index` is the cursor indicate current position | |
int stack[10000] = {0}, stack_index = 0; | |
// Functions define | |
void push(int x); | |
int pop(); | |
int size(); | |
void clear(); | |
void decToBin(int x); | |
// End functions define | |
int main() { | |
int decimal; | |
scanf("%d", &decimal); | |
decToBin(decimal); | |
return 0; | |
} | |
// Push a number into stack | |
void push(int x) { | |
stack[stack_index] = x; | |
++stack_index; | |
} | |
// Get the top element from the stack and remove it from the stack | |
int pop() { | |
--stack_index; | |
return stack[stack_index]; | |
} | |
// Get the size of the stack | |
int size() { | |
return stack_index; | |
} | |
// Clear the stack | |
void clear() { | |
stack_index = 0; | |
} | |
// Convert a decimal number into a binary number | |
void decToBin(int x) { | |
int decimal = x, remainder = 1; | |
if (decimal == 0) { | |
putchar('0'); | |
} else { | |
// If decimal number is less than zero | |
bool isNegative = x < 0; | |
// If `decimal` less than zero, turn it to positive number | |
decimal = decimal < 0 ? decimal * -1 : decimal; | |
while (decimal != 0) { | |
remainder = decimal % 2; | |
decimal /= 2; | |
push(remainder); | |
} | |
// If decimal number is less than zero, don't forget to print '-' | |
if (isNegative) putchar('-'); | |
while (size() != 0) { | |
printf("%d", pop()); | |
} | |
} | |
printf("\n"); | |
// Clear the stack for next input | |
clear(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment