0

I have to convert a Number of Type Long in C to a BCD (Binary Coded Decimal) Number with 4 Bits each. I can only use Bitwise shifting and Bitoperations. Can anyone help me achiving this. At the moment i have no idea how to reach my goal.

unsigned long convertBinaryToBCD(unsigned long number){
int number_t_conv = number;
int num_digit = 0;
int count_digits = countNumberDigits(number);

for(num_digit = 0; num_digit <= count_digits; num_digit++){

}
return (((number_t_conv/100) << 8) | ((number_t_conv/10) << 4) | (number_t_conv % 10));
};
  • 2
    It is not clear what you **cannot* use. `sprintf()`? Additions between integers? Subtractions? Examples of inputs and desired outputs? – Roberto Caboni Jan 13 '20 at 08:24
  • I Have to achieve it without Arrays. I have to have an output like this: Input: 101 - 0000 0000 | 0000 0000 | 0000 0000 | 0110 0101 BCD: 257 - 0000 0000 | 0000 0000 | 0000 0001 | 0000 0001 Binary: 101 - 0000 0000 | 0000 0000 | 0000 0000 | 0110 0101 –  Jan 13 '20 at 08:26
  • Does this [Convert integer from (pure) binary to BCD](https://stackoverflow.com/questions/13247647/convert-integer-from-pure-binary-to-bcd) helps you ? – Achal Jan 13 '20 at 08:32
  • 2
    *"At the moment i have no idea how to reach my goal."* You should know about loops and bit operators. **Please show your attempt so far, and explain where you are stuck.** If you have nothing, you haven't tried hard enough. – user694733 Jan 13 '20 at 08:53

1 Answers1

3
  • The long in the C program's memory will be raw binary, so the first step is to split it up into decimal format digits.
  • This is done by repeatedly dividing the number by 10 and grabbing the remainder. The LS digit of the number is always n % 10, and when you do n / 10 you "shift" the decimal number one digit to the right.
  • Once you have an array of digits, printing it as BCD is trivial - it's just printing a binary number in string format.

Start by coding the above program and once you have it working, try to achieve the same with whatever artificial nonsense requirements you have from your teacher.

Lundin
  • 195,001
  • 40
  • 254
  • 396