Inspired by fb, Bowsayge decided to write a decimal integer
to binary string converter. Perhaps some of the experienced
C programmers here can critique it. It allocates probably
way too much memory, but it should certainly handle 64-bit
cpus :)
#include <stdio.h>
#include <stdlib.h>
char * to_binary (unsigned long value) {
const int maxdata = 100;
char * data = malloc(maxdata+ 1);
int pos = 0;
int pos2 = 0;
if (0 == data) return 0;
if (0 == value) {
return strcpy (data, "0");
}
while (value > 0) {
if (pos >= maxdata) {
printf ("ran out of memory\n");
exit(EXIT_FAILU RE);
}
data [pos++] = '0' + (value & 1);
value >>= 1;
}
data[pos--] = 0;
for (pos2 = 0; pos2 < pos; pos2++, pos--) {
char temp = data[pos];
data[pos] = data[pos2];
data[pos2] = temp;
}
return data;
}
int main (int argc, const char * argv [])
{
int ii = 0;
while (ii < argc) {
unsigned long num = ii < 1 ? 5 : atol(argv[ii]);
char * str = to_binary(num);
if (0 == str) return EXIT_FAILURE;
printf ("%lu (decimal) = %s (binary)\n", num, str);
free(str);
ii++;
}
return EXIT_SUCCESS;
}
to binary string converter. Perhaps some of the experienced
C programmers here can critique it. It allocates probably
way too much memory, but it should certainly handle 64-bit
cpus :)
#include <stdio.h>
#include <stdlib.h>
char * to_binary (unsigned long value) {
const int maxdata = 100;
char * data = malloc(maxdata+ 1);
int pos = 0;
int pos2 = 0;
if (0 == data) return 0;
if (0 == value) {
return strcpy (data, "0");
}
while (value > 0) {
if (pos >= maxdata) {
printf ("ran out of memory\n");
exit(EXIT_FAILU RE);
}
data [pos++] = '0' + (value & 1);
value >>= 1;
}
data[pos--] = 0;
for (pos2 = 0; pos2 < pos; pos2++, pos--) {
char temp = data[pos];
data[pos] = data[pos2];
data[pos2] = temp;
}
return data;
}
int main (int argc, const char * argv [])
{
int ii = 0;
while (ii < argc) {
unsigned long num = ii < 1 ? 5 : atol(argv[ii]);
char * str = to_binary(num);
if (0 == str) return EXIT_FAILURE;
printf ("%lu (decimal) = %s (binary)\n", num, str);
free(str);
ii++;
}
return EXIT_SUCCESS;
}
Comment