Go Down

Topic: Convert Dec to BCD (Read 6 times) previous topic - next topic

gardner

Would this help?

Code: [Select]
/* Encode the input number into BCD into the output buffer, of
* the specified length.  The BCD encoded number is right-justified
* in the field.  Return the number of digits converted, or -1 if the
* buffer was not big enough for the whole conversion.
*/
int bcd_encode(unsigned long number, unsigned char *buffer, int length)
{
  unsigned char *p;
  unsigned char n, m, bval, digit;

   n = 0;     /* nibble count */
   m = 0;     /* converted digit count */
   bval = 0;  /* the bcd encoded value */


   /* Start from the righthand end of the buffer and work
    * backwards
    */
   p = buffer + length - 1;
   while (p >= buffer) {

       if (number != 0) {
          digit = number % 10;
          number = number / 10;
          m++;
       } else
          digit = 0;

       /* If we have an odd-numbered digit position
        * then save the byte and move to the next buffer
        * position.  Otherwise go convert another digit
        */
       if (n & 1) {
          bval |= digit << 4;
          *p-- = bval;
          bval = 0;
       } else
          bval = digit;

       n++;
   }

   /* If number is not zero, then we have run out of room
    * and the conversion didn't fit.  Return -1;
    */
   if (number)
      return(-1);

   /* return the number of converted digits
    */
   return(m);
}


Not guaranteed to be super fast -- it does do long division.  But it should work.

Go Up