Skip to content

Instantly share code, notes, and snippets.

@gmelodie
Created July 7, 2023 14:27
Show Gist options
  • Save gmelodie/fa4b0853702d1f7fa182abf532f8655e to your computer and use it in GitHub Desktop.
Save gmelodie/fa4b0853702d1f7fa182abf532f8655e to your computer and use it in GitHub Desktop.
dec2bin in C without using arrays
#include <stdio.h>
#include <math.h>
int main(int argc, char *argv[]) {
int dec;
scanf("%d", &dec);
// figure out bits needed to represent number
// 1. you can log(dec) base 2 or...
// 2. what ill do next
int pot = 0;
while(pow(2, pot) <= dec) {
pot++;
}
pot--; // you always go one further (edge case 1024 for example)
for(int i = pot; i >= 0; i--) {
// does 2**i fit in dec?
if(pow(2, i) <= dec) {
printf("1");
dec -= pow(2, i);
} else {
printf("0");
}
}
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment