unvisibleman

dec2gray and gray2dec

Mar 20th, 2016
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | None | 0 0
  1.         // Переводчик из десятичного числа в код Грея
  2.         private char[] Dec2Gray(int a)
  3.         {
  4.             char[] digits = new char[2];
  5.             digits[0] = '0'; digits[1] = '1';
  6.             string res = "";
  7.             int d;
  8.             while (a != 0)
  9.             {
  10.                 d = a % 2;
  11.                 res = digits[d] + res;
  12.                 a = a / 2;
  13.             }
  14.  
  15.             char[] dec = new char[res.Length];
  16.             for (int i = 0; i < res.Length; i++)
  17.             {
  18.                 dec[i] = res[i];
  19.  
  20.             }
  21.  
  22.             char[] gray = new char[res.Length];
  23.             gray[0] = dec[0];
  24.             for (int i = 1; i < res.Length; i++)
  25.             {
  26.                 if (dec[i - 1] == '1')
  27.                 {
  28.                     if (dec[i] == '1') gray[i] = '0';
  29.                     else gray[i] = '1';
  30.                 }
  31.                 else gray[i] = dec[i];
  32.  
  33.             }
  34.             return gray;
  35.         }
  36.  
  37.         // Переводчик из кода Грея в десятичное число
  38.         private int Gray2Dec(string gray)
  39.         {
  40.             char[] bin = new char[gray.Length];
  41.             bin[0] = gray[0];
  42.             int flag = 0;
  43.             if (gray[0] == '1') flag = 1;
  44.  
  45.             for (int i = 1; i < gray.Length; i++)
  46.             {
  47.                 if (flag % 2 == 1)
  48.                 {
  49.                     if (gray[i] == '1') { bin[i] = '0'; flag++; }
  50.                     else bin[i] = '1';
  51.                 }
  52.                 else { bin[i] = gray[i]; if (bin[i] == '1') flag++; }
  53.             }
  54.  
  55.             char[] digits = new char[2];
  56.             digits[0] = '0'; digits[1] = '1';
  57.             int dec, ves, j;
  58.             dec = 0; ves = 1;
  59.             for (int i = (bin.Length) - 1; i >= 0; i--)
  60.             {
  61.                 j = 0;
  62.                 while (digits[j] != bin[i]) j++;
  63.                 dec = dec + ves * j;
  64.                 ves = ves * 2;
  65.             }
  66.  
  67.             return dec;
  68.         }
Advertisement
Add Comment
Please, Sign In to add comment