I've made a very simple program that takes integer number arguments either with plus/minus sign or without them, and print the number in binary format.
binary.c
#include <stdio.h>
void printBinary(int);
int toInt(int*, char[]);
int handleProgram(char[]);
int main(int argc, char *argv[])
{
return handleProgram(argv[1]);
}
int handleProgram(char param[])
{
int number, state;
if( toInt( &number, param ) != -1 )
{
printBinary(number);
state = 0;
}
else
{
printf("\tmain()::Exiting program...\n");
state = -1;
}
return state;
}
void printBinary(int number)
{
for (int i = 31; i >= 0; i--)
{
if (number >> i & 1 == 1)
putchar('1');
else
putchar('0');
if (i != 0)
{
if (i % 4 == 0)
putchar(' ');
if (i % 16 == 0)
printf(": ");
}
}
printf("\n");
}
int toInt(int *num, char param[])
{
*num = 0;
int sign = 1;
int i = 0;
if(param == NULL)
{
printf("\ttoInt()::No parameter, please enter a valid number!\n");
return -1;
}
if(param[i] == '-')
{
sign = -1;
i++;
}
else if( param[i] == '+' )
{
i++;
}
// check that a number exist
if(param[i] == '\0')
{
printf("\ttoInt()::No number detected, please enter a valid number\n");
return -1;
}
for(; param[i] != '\0'; i++)
{
if(param[i] >= '0' && param[i] <= '9')
*num = 10* *num + param[i] - '0';
else
{
printf("\ttoInt()::Invalid parameter, please enter a valid number!\n");
return -1;
}
}
*num *= sign;
return 0;
}
Sample output: positive and negative cases
D:\C\chapter2>gcc binary.c -o binary.exe D:\C\chapter2>binary 3 0000 0000 0000 0000 : 0000 0000 0000 0011 D:\C\chapter2>binary +3 0000 0000 0000 0000 : 0000 0000 0000 0011 D:\C\chapter2>binary -3 1111 1111 1111 1111 : 1111 1111 1111 1101 D:\C\chapter2>binary +3s toInt()::Invalid parameter, please enter a valid number! main()::Exiting program... D:\C\chapter2>binary -3s toInt()::Invalid parameter, please enter a valid number! main()::Exiting program... D:\C\chapter2>binary s toInt()::Invalid parameter, please enter a valid number! main()::Exiting program... D:\C\chapter2>binary + toInt()::No number detected, please enter a valid number main()::Exiting program... D:\C\chapter2>binary - toInt()::No number detected, please enter a valid number main()::Exiting program... D:\C\chapter2>binary toInt()::No parameter, please enter a valid number! main()::Exiting program...
Any ideas for a better approach (where to fix, what to do about negative cases, any more functions need)?
strtol
(in stdlib) is the way to go (the man page includes a comprehensive example on how to use it), and can reduce your code by half. Even though your code doesn't require IO performance, it's good practice using a buffer for constructing your output and print only once rather than on multiple little chunks. \$\endgroup\$