2&10&16进制互转

作者:追风剑情 发布于:2017-11-1 14:57 分类:C#

示例

using System;
using System.Collections.Generic;

namespace HexTest
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = 255;
            Console.WriteLine("Decimal={0}, Hex8={1}, Hex24={2}, Hex32={3}", num,
                DecimalToHex8(num), DecimalToHex24(num), DecimalToHex32(num));
            Console.WriteLine("IntToBinary: {0}", IntToBinary(num));
            Console.WriteLine("HexToDecimal: {0}", HexToDecimal("FF0000"));

            Console.ReadLine();
        }

        public static string IntToBinary(int val, int bits=32)
        {
            string final = "";

            for (int i = bits; i > 0; )
            {
                if (i == 8 || i == 16 || i == 24) final += " ";
                final += ((val & (1 << --i)) != 0) ? '1' : '0';
            }
            return final;
        }

        public static string DecimalToHex8(int num)
        {
            num &= 0xFF;
            return num.ToString("X2");
        }

        public static string DecimalToHex24(int num)
        {
            num &= 0xFFFFFF;
            return num.ToString("X6");
        }

        public static string DecimalToHex32 (int num)
        {
            return num.ToString("X8");
        }

        public static int HexToDecimal(string hex)
        {
            return Convert.ToInt32(hex, 16);
        }

        public static int HexToDecimal(char ch)
        {
            switch (ch)
            {
                case '0': return 0x0;
                case '1': return 0x1;
                case '2': return 0x2;
                case '3': return 0x3;
                case '4': return 0x4;
                case '5': return 0x5;
                case '6': return 0x6;
                case '7': return 0x7;
                case '8': return 0x8;
                case '9': return 0x9;
                case 'a':
                case 'A': return 0xA;
                case 'b':
                case 'B': return 0xB;
                case 'c':
                case 'C': return 0xC;
                case 'd':
                case 'D': return 0xD;
                case 'e':
                case 'E': return 0xE;
                case 'f':
                case 'F': return 0xF;
            }
            return 0xF;
        }
    }
}

测试

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号