I wrote a code that requests user input and then converts binary to bcd then back to binary using bitwise operations. While I think my code is good I want to know if there is a better way to write the code. Is there also a way to keep the code mostly the same but getting rid of the arrays for printing out the bit positions?
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#define UINT_MAXIMUM 4294967294
#define MAX_NUMBER 99999999
void printBits(unsigned long number);
unsigned long convertBinaryToBCD(unsigned long number);
unsigned long convertBCDToBinary(unsigned long number);
unsigned long printNumber(unsigned long input)
{
printf(" Input: ");
printf("%10lu", input);
printBits(input);
unsigned long output_bcd = convertBinaryToBCD(input);
unsigned long output_binary = convertBCDToBinary(output_bcd);
printf(" BCD: ");
if(output_bcd != UINT_MAX)
{
printf("%10lu", output_bcd);
printBits(output_bcd);
}
printf("Binary: ");
if(output_binary != UINT_MAX)
{
printf("%10lu", output_binary);
printBits(output_binary);
}
return 0;
}
void printBits(unsigned long number)
{
int bit_position[32];
printf(" - ");
int counter = 0;
for(counter = 32; counter > 0; counter--)
{
bit_position[counter] = number % 2;
number = number / 2;
}
for(counter = 1; counter <= 32; counter++)
{
if(counter == 9 || counter == 17 || counter == 25)
{
printf(" | ");
}
if(counter == 5 || counter == 13 || counter == 21 || counter == 29)
{
printf(" ");
}
printf("%d", bit_position[counter]);
}
printf("\n");
}
int main(int argc, char *argv[])
{
unsigned long number;
number = strtoul(argv[1], NULL, 10);
if(number > UINT_MAXIMUM)
{
printf("too big\n");
return 0;
}
printNumber(number);
return 0;
}
unsigned long convertBinaryToBCD(unsigned long number)
{
if (number > MAX_NUMBER)
{
return UINT_MAX;
}
if(number < 100)
{
return (((number/10)+((number/100)*6))*16)+(number%10);
}
unsigned long sub_number_one = ((number / 12) << 5);
unsigned long sub_number_two = (number % 10) ;
unsigned long temporary;
while(sub_number_two != 0)
{
temporary = sub_number_one & sub_number_two;
sub_number_one = sub_number_one ^ sub_number_two;
sub_number_two = temporary << 1;
}
return sub_number_one;
}
unsigned long convertBCDToBinary(unsigned long number)
{
if (number == UINT_MAX)
{
return UINT_MAX;
}
if(number < 100)
{
return (((number >> 8) * 100) + ((number >> 4) * 10) + (number & 0xF));
}
unsigned long sub_number_one = (number >> 8) * 100;
unsigned long sub_number_two = (number & 0x0F);
unsigned long temporary;
while(sub_number_two != 0)
{
temporary = sub_number_one & sub_number_two;
sub_number_one = sub_number_one ^ sub_number_two;
sub_number_two = temporary << 1;
}
return sub_number_one;
}
printBits
. C array indexing starts at 0, so valid subscripts tobit_position
are 0..31. \$\endgroup\$