It's been a long time since I've heard the terms BCD
or Binary Coded Decimal
. Keep in mind that BCD was primarily a hardware encoding of integers provided by one particular manufacturer of main frame computers. There were computer performance issues when using BCD.
The best way to implement a BCD number would be an array of 4 bit integer values.
One good habit the code demonstrates is that all if
statements and loops wraps the code in braces ({
and }
). Thank you for that!
Magic Numbers
##Magic Numbers
ThereThere are Magic Numbers in the void printBits(unsigned long number)
function (32, 9, 17, 25, 5, 13, 21 and 29), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.
Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.
Unused Header Files
##Unused Header Files
TheThe program includes limits.h
and string.h
but the contents of these files are not used by the code in the program. In the case of string.h
it might be better to remove the #include
. In the case of limits.h
it might be better to use the limits provided. It is better to not include files that aren't being used since this will decrease the size of the code being compiled and might improve build times. The #include
directive literally copies the header file into the intermediate file that is compiled after the C pre-processor is run.
Algorithm
##Algorithm
ItIt might be better to prompt the user for the number to be converted rather than use argv
as the source of the input. Even if argv
continues to be the source of the input, it would be better to check argc
to see if there are enough arguments and either prompt the user for a number in screen input, or report an error and quit.
Readability
##Readability
TheThe some of the functions (printBits
and convertBinaryToBCD
) might be easier to read if there was vertical spacing in the functions.
Off by One Bug
##Off by One Bug
AsAs noted by @1201ProgramAlarm there is an off by one bug
in void printBits(unsigned long number)
, the code is accessing one invalid memory location bit_position[32]
and ignoring bit_position[0]
.
It is also not clear why bit_position is 32 bits rather than 64 bits, since the code is primarily using unsigned long rather than unsigned int.