user6652930
user6652930

Reputation:

Bitshifting of a number in C

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));
};

Upvotes: 0

Views: 427

Answers (1)

Lundin
Lundin

Reputation: 215330

  • 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.

Upvotes: 3

Related Questions