Created
September 5, 2023 22:19
-
-
Save sixem/c0959c3cbab8a1b38f15da1884ccfe44 to your computer and use it in GitHub Desktop.
Basic decimal to binary in C
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> | |
#include <stdlib.h> | |
int main() { | |
int decimal; | |
int *sequence = NULL; | |
int size = 0; | |
printf("Enter a decimal number: "); | |
scanf("%d", &decimal); | |
if(decimal < 0) { | |
printf("Invalid input\n"); | |
return 0; | |
} else if(decimal == 0) { | |
printf("0\n"); | |
return 0; | |
} | |
while(decimal > 0) { | |
sequence = (int *)realloc(sequence, sizeof(int) * (size + 1)); | |
sequence[size] = decimal % 2; | |
decimal /= 2; | |
size++; | |
} | |
for(int i = size - 1; i >= 0; i--) { | |
printf("%d", sequence[i]); | |
} | |
free(sequence); | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment