Skip to content

Instantly share code, notes, and snippets.

@Dynesshely
Created September 28, 2023 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dynesshely/ad428abf48edba512b02c60705aa426e to your computer and use it in GitHub Desktop.
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.
#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