最新の更新情報

2012年5月
« 4月    
 12345
6789101112
13141516171819
20212223242526
2728293031  

本ブログのURL

qrcode.png

お天気

 
このブログ「吟遊詩人の戯言」 の記事検索...

グレイコード変換


キーワード(クリックで関連記事が読めます) → ,

関連記事



 
 

仕事で必要になったんで、ちょろっと、グレイコード変換クラス、書き起こしてみましたわん!

バグってたら、すまそ(ww

C#:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4.  
  5. namespace bMountLibrary
  6. {
  7.     public class GrayCode
  8.     {
  9.         public GrayCode()
  10.         {
  11.         }
  12.        
  13.         private const uint MASK_PATTERN = 0x00000001;
  14.  
  15.         //-----------------------------------
  16.         //バイナリをグレイコードへ変換
  17.         //
  18.         // dat      : 元のバイナリ値
  19.         //
  20.         // return   : グレイコード
  21.         //-----------------------------------
  22.         static public uint BinToGrayCode(uint dat)
  23.         {
  24.             return dat ^ (dat>> 1) ;
  25.         }
  26.        
  27.         //-----------------------------------
  28.         //バイナリをグレイコードへ変換
  29.         //
  30.         // dat      : 元のグレイコード値
  31.         // bitCount : 有効ビット数(1~32)
  32.         //
  33.         // return   : バイナリ値
  34.         //-----------------------------------
  35.         static public uint GrayCodeToBin(uint dat, int bitCount)
  36.         {
  37.             uint result = 0;
  38.             uint mask1;
  39.             uint mask2;
  40.             uint tmp1;
  41.             uint tmp2;
  42.  
  43.             if ((bitCount <1) || (bitCount> 32))
  44.             {
  45.                 return 0;
  46.             }
  47.  
  48.             uint mask = MASK_PATTERN <<(bitCount - 1);
  49.  
  50.             result = dat & mask;
  51.  
  52.             for (int i = 1 ; i <bitCount; i++)
  53.             {
  54.                 mask1 = (mask>> (i -1));
  55.                 mask2 = (mask>> (i   ));
  56.  
  57.                 tmp1 = result & mask1;
  58.                 tmp2 = dat    & mask2;
  59.  
  60.                 if ((tmp1 != 0) && (tmp2 == 0))
  61.                 {
  62.                     result |= mask2;
  63.                 }
  64.  
  65.                 if ((tmp1 == 0) && (tmp2 != 0))
  66.                 {
  67.                     result |= mask2;
  68.                 }
  69.  
  70.             }
  71.  
  72.             return result;
  73.         }
  74.  
  75.     }
  76. }

 
 
 
 

Leave a Reply

  

  

  

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <img localsrc="" alt="">