Advertisement
paulogp

Binary2BCD

Jul 13th, 2011
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.98 KB | None | 0 0
  1. /* Converte número binário (unsigned) 16-bit no seu equivalente decimal (formato BCD compactado). */
  2.  
  3.  
  4. // Apple Xcode
  5. //
  6. //  main.c
  7. //
  8. //  Created by Paulo G.P. on 6/27/11.
  9. //
  10.  
  11. #include <stdio.h>
  12.  
  13.  
  14. void adjust(unsigned char *p)
  15. {
  16.     unsigned char t = *p + 3;
  17.     if (t & 0x08) *p = t;
  18.     t = *p + 0x30;
  19.     if (t & 0x80) *p = t;
  20. }
  21.  
  22. unsigned long binary2bcd(unsigned int n)
  23. {
  24.     unsigned char bcd[3] = {0, 0, 0};
  25.  
  26.     for (int i = 0; i < 16; ++i) {
  27.         adjust(&bcd[0]);
  28.         adjust(&bcd[1]);
  29.         adjust(&bcd[2]);
  30.  
  31.         bcd[2] <<= 1;
  32.         if (bcd[1] & 0x80) ++bcd[2];
  33.  
  34.         bcd[1] <<= 1;
  35.         if (bcd[0] & 0x80) ++bcd[1];
  36.  
  37.         bcd[0] <<= 1;
  38.         if (n & 0x8000) ++bcd[0];
  39.  
  40.         n <<= 1;
  41.     }
  42.  
  43.     return (unsigned long)(bcd[2] << 16) | (bcd[1] << 8) | bcd[0];
  44. }
  45.  
  46. int main (int argc, const char * argv[])
  47. {
  48.     int the_example = 10;
  49.  
  50.     printf("resultado: %lu\n", binary2bcd(the_example));
  51.  
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement