Go Down

Topic: Convert Dec to BCD (Read 6865 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.

awyork

#16
Dec 19, 2014, 04:56 am Last Edit: Dec 19, 2014, 04:57 am by awyork
If you just want to print BCD to the serial terminal, just use the Serial.print(x, HEX).  It will work this is because BCD base 16 is the same as HEX.

Here are two quick and crude functions.  The only work for two digits, but you can modify as needed.  Arduino byte only supports two digit anyway.

Code: [Select]

byte dec_to_bcd(byte dec)
{
byte result = 0;

result |= (dec / 10) << 4;
result |= (dec % 10) << 0;

return result;
}

byte bcd_to_dec(byte bcd)
{
byte result = 0;

result += ((bcd & 0b11110000) >> 4) * 10;
result += (bcd & 0b00001111);

return result;
}


Enjoy.

robtillaart

#17
Dec 19, 2014, 09:45 am Last Edit: Dec 19, 2014, 10:22 am by robtillaart
Here a discussion about a fast dec2bcd and some more - http://forum.arduino.cc/index.php?topic=185235.0 -

fastest functions so far
Code: [Select]

uint8_t bcd2dec2(uint8_t n)  // takes 1384 usec for 1000 calls
{
  return n - 6 * (n/16);
}

uint8_t dec2bcd2(uint8_t n)  // takes 2244 usec for 1000 calls
{
  uint16_t a = n;
  byte b = (a*103) >> 10;  // this equals:  b = a/10;
  return  n + b*6;
}


update:
- removed faulty code
- figures from UNO & IDE1.5.8
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Go Up