C#,数值计算——灰色码(Gray Codes)的计算方法与源代码

一个 n位灰色码 序列,就是2的n次方 个 整数;

第一个数字为0;

相邻两个数字的二进制只有一位不一样;

第一个数字和最后一个数字的二进制也只有一位不一样。

using System;

namespace Legalsoft.Truffer
{
    /// <summary>
    /// Gray Codes
    /// </summary>
    public class Gray
    {

        public uint gray(uint n)
        {
            return n ^ (n >> 1);
        }

        public uint invgray(uint n)
        {
            int ish = 1;
            uint ans = n;
            uint idiv;
            for (; ; )
            {
                ans ^= (idiv = (uint)(ans >> ish));
                if (idiv <= 1 || ish == 16)
                {
                    return ans;
                }
                ish <<= 1;
            }
        }
    }
}
 

猜你喜欢

转载自blog.csdn.net/beijinghorn/article/details/131445541
今日推荐