This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

BCD conversion code

By: a guest on Oct 14th, 2010  |  syntax: C  |  size: 1.46 KB  |  views: 135  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <stdio.h>
  2.  
  3. // This might not be very portable but works for Linux/Windows
  4. union
  5. {
  6.   unsigned char byte[4];
  7.   unsigned long v;
  8. } reg;
  9.  
  10. // internal dump of intermediate steps so you can see what's happening
  11. void dump(char *s)
  12. {
  13.   int i;
  14.   printf("%s: ",s);
  15.   for (i=sizeof(reg.byte)-1;i>=0;i--) printf("%x ",reg.byte[i]);
  16.   printf("\n");
  17. }
  18.  
  19.  
  20. int main(int argc, char **argv)
  21. {
  22.   char buf[65];
  23.   int n,i=0;
  24.   // Get a number to play with
  25.   printf("Number (decimal)?");
  26.   gets(buf);
  27.   reg.v=atoi(buf);
  28.   // loop 8 times
  29.   while (i!=8)
  30.     {
  31.       printf("%d\n",i++);  // debug output
  32.       dump("Base");
  33.       // The idea is we are going to shift the number left
  34.       // 8 places to the "new" location
  35.       // but.. on each shift we will look to see if a
  36.       // BCD digit is >=5... if so the next shift shoul
  37.       // give us 10 but will instead give us A
  38.       // so if that's the case, add 3 so you get 8 (or 9 or 10, etc.)
  39.       // and double that will be 0x10, 0x11, 0x12...
  40.       // Since the max output is 255 there is no reason
  41.       // to test the top digit
  42.       if ((reg.byte[1]&0xF)>=5)  reg.byte[1]+=3;
  43.       if ((reg.byte[1]>>4&0xF)>=5)  reg.byte[1]+=0x30;
  44.       dump("Add");
  45.       // so now that we've adjusted things, shift
  46.       reg.v<<=1;
  47.       dump("Shift");
  48.     }
  49.   // final result is in reg.byte[2] (MSD) and packed in reg.byte[1]
  50.   printf("\nResult: %d%d%d\n",reg.byte[2]&0xF,reg.byte[1]>>4,reg.byte[1]&0xF);
  51. }
clone this paste RAW Paste Data