Skip to content

Instantly share code, notes, and snippets.

@nunq
Created August 4, 2023 06:46
Show Gist options
  • Save nunq/bc45dff61ac47892c68d9ce966151245 to your computer and use it in GitHub Desktop.
Save nunq/bc45dff61ac47892c68d9ce966151245 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int to_dec(char *bin) {
unsigned int dec = 0;
unsigned int weight = 1;
bin += 8 - 1;
for(int i=0; i<8; i++, --bin) {
if(*bin == '1') {
dec += weight;
}
weight *= 2;
}
return dec;
}
int main(int argc, char *argv[]) {
if (argc != 2 || strlen(argv[1]) % 8 != 0 || strlen(argv[1]) == 0) {
printf("err: input not divisible by 8 or is 0\n");
exit(1);
}
char buf[8];
for(int i=0; i<strlen(argv[1]); i+=8) {
for(int j=0; j<8; j++) {
buf[j] = argv[1][i+j];
}
printf("%c", (char)to_dec(buf));
}
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment