反转位元

作者:追风剑情 发布于:2018-8-24 21:30 分类:Algorithms

示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("***byte->bit string->byte***");
            string bitstr, bitstr_rev;
            byte rev;
            //部分测试数据
            for (int i = 250; i <= 255; i++)
            {
                bitstr = ToBitString((byte)i);
                rev = BitReverse((byte)i);
                bitstr_rev = ToBitString(rev);
                Console.WriteLine(string.Format("{0}->{1}->{2}, Rev:{3}->{4}", i, bitstr, ToByte(bitstr), rev, bitstr_rev));
            }

            //反转位元要用到的常量
            Console.WriteLine(string.Format("10101010={0}", ToByte("10101010")));
            Console.WriteLine(string.Format("01010101={0}", ToByte("01010101")));
            Console.WriteLine(string.Format("11001100={0}", ToByte("11001100")));
            Console.WriteLine(string.Format("00110011={0}", ToByte("00110011")));
            Console.WriteLine(string.Format("11110000={0}", ToByte("11110000")));
            Console.WriteLine(string.Format("00001111={0}", ToByte("00001111")));

            Console.Read();
        }

        //反转位元
        static byte BitReverse(byte b)
        {
            //相邻位元组交换位置
            int x = b;
            x = ((x & 170) >> 1) | ((x & 85) << 1);//每组1个位元
            x = ((x & 204) >> 2) | ((x & 51) << 2);//每组2个位元
            x = ((x & 240) >> 4) | ((x & 15) << 4);//每组4个位元
            return (byte)x;
        }

        static string ToBitString(byte b)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 7; i >= 0; i--)
            {
                sb.Append(((1 << i) & b)>>i);
            }
            return sb.ToString();
        }

        static byte ToByte(string bitstr)
        {
            int b = 0;
            for (int i = 0; i <= 7; i++)
            {
                if (bitstr[i] == '1')
                    b |= (1 << (7-i));
            }
                return (byte)b;
        }
    }
}

1111.png

标签: Algorithms

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号