Skip to content

Instantly share code, notes, and snippets.

@duckinator
Created November 14, 2009 18:20
Show Gist options
  • Save duckinator/234676 to your computer and use it in GitHub Desktop.
Save duckinator/234676 to your computer and use it in GitHub Desktop.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
char *bin2dec(char *str)
{
char *ret = malloc(sizeof(int)*20);
char *tmp = malloc(sizeof(int));
int dec = 0;
int digit = 0;
int r = 0;
int bit_weight = 0;
for (r = strlen(str)-1; r >= 0; r--) {
strncpy(tmp, &str[r], 1);
digit = atoi(tmp);
bit_weight = (int)pow(2,(strlen(str)-r-1));
if ( digit == 1 ) {
dec += bit_weight;
}
}
sprintf(ret, "%i", dec);
return ret;
}
char *dec2bin(int num)
{
char *bin = malloc(sizeof(int)*20);
char *tmp = malloc(sizeof(int)*20);
int r = 0;
while ( num > 0 ) {
if ( (num%2) != 0 ) {
r = 1;
} else {
r = 0;
}
sprintf(tmp, "%i%s", r, bin);
strcpy(bin, tmp);
memset(tmp, 0, sizeof(int)*20);
num=num/2;
}
return bin;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment