欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# 2进制、8进制、10进制、16进制...各种进制间的转换(二)搜集的各种转换及方法

程序员文章站 2022-05-16 09:52:01
/// /// 十进制转换为二进制 /// /// /// public static string DecToBin(string x) { string z = null; int X = Convert.ToInt32(x); ... ......

 

/// <summary>
        /// 十进制转换为二进制
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string dectobin(string x)
        {
            string z = null;
            int x = convert.toint32(x);
            int i = 0;
            long a, b = 0;
            while (x > 0)
            {
                a = x%2;
                x = x/2;
                b = b + a*pow(10, i);
                i++;
            }
            z = convert.tostring(b);
            return z;
        }

        /// <summary>
        /// 16进制转ascii码
        /// </summary>
        /// <param name="hexstring"></param>
        /// <returns></returns>
        public static string hextoascii(string hexstring)
        {
            stringbuilder sb = new stringbuilder();
            for (int i = 0; i <= hexstring.length - 2; i += 2)
            {
                sb.append(
                    convert.tostring(
                        convert.tochar(int32.parse(hexstring.substring(i, 2),
                                                   system.globalization.numberstyles.hexnumber))));
            }
            return sb.tostring();
        }

        /// <summary>
        /// 十进制转换为八进制
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string dectootc(string x)
        {
            string z = null;
            int x = convert.toint32(x);
            int i = 0;
            long a, b = 0;
            while (x > 0)
            {
                a = x%8;
                x = x/8;
                b = b + a*pow(10, i);
                i++;
            }
            z = convert.tostring(b);
            return z;
        }

        /// <summary>
        /// 十进制转换为十六进制
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string dectohex(string x)
        {
            if (string.isnullorempty(x))
            {
                return "0";
            }
            string z = null;
            int x = convert.toint32(x);
            stack a = new stack();
            int i = 0;
            while (x > 0)
            {
                a.push(convert.tostring(x%16));
                x = x/16;
                i++;
            }
            while (a.count != 0)
                z += tohex(convert.tostring(a.pop()));
            if (string.isnullorempty(z))
            {
                z = "0";
            }
            return z;
        }

        /// <summary>
        /// 二进制转换为十进制
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string bintodec(string x)
        {
            string z = null;
            int x = convert.toint32(x);
            int i = 0;
            long a, b = 0;
            while (x > 0)
            {
                a = x%10;
                x = x/10;
                b = b + a*pow(2, i);
                i++;
            }
            z = convert.tostring(b);
            return z;
        }

        /// <summary>
        /// 二进制转换为十进制,定长转换
        /// </summary>
        /// <param name="x"></param>
        /// <param name="ilength"></param>
        /// <returns></returns>
        public static string bintodec(string x, short ilength)
        {
            stringbuilder sb = new stringbuilder();
            int icount = 0;

            icount = x.length/ilength;

            if (x.length%ilength > 0)
            {
                icount += 1;
            }

            int x = 0;

            for (int i = 0; i < icount; i++)
            {
                if ((i + 1)*ilength > x.length)
                {
                    x = convert.toint32(x.substring(i*ilength, (x.length - ilength)));
                }
                else
                {
                    x = convert.toint32(x.substring(i*ilength, ilength));
                }
                int j = 0;
                long a, b = 0;
                while (x > 0)
                {
                    a = x%10;
                    x = x/10;
                    b = b + a*pow(2, j);
                    j++;
                }
                sb.appendformat("{0:d2}", b);
            }
            return sb.tostring();
        }

        /// <summary>
        /// 二进制转换为十六进制,定长转换
        /// </summary>
        /// <param name="x"></param>
        /// <param name="ilength"></param>
        /// <returns></returns>
        public static string bintohex(string x, short ilength)
        {
            stringbuilder sb = new stringbuilder();
            int icount = 0;

            icount = x.length/ilength;

            if (x.length%ilength > 0)
            {
                icount += 1;
            }

            int x = 0;

            for (int i = 0; i < icount; i++)
            {
                if ((i + 1)*ilength > x.length)
                {
                    x = convert.toint32(x.substring(i*ilength, (x.length - ilength)));
                }
                else
                {
                    x = convert.toint32(x.substring(i*ilength, ilength));
                }
                int j = 0;
                long a, b = 0;
                while (x > 0)
                {
                    a = x%10;
                    x = x/10;
                    b = b + a*pow(2, j);
                    j++;
                }
                //前补0
                sb.append(dectohex(b.tostring()));
            }
            return sb.tostring();
        }

        /// <summary>
        /// 八进制转换为十进制
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string octtodec(string x)
        {
            string z = null;
            int x = convert.toint32(x);
            int i = 0;
            long a, b = 0;
            while (x > 0)
            {
                a = x%10;
                x = x/10;
                b = b + a*pow(8, i);
                i++;
            }
            z = convert.tostring(b);
            return z;
        }


        /// <summary>
        /// 十六进制转换为十进制
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string hextodec(string x)
        {
            if (string.isnullorempty(x))
            {
                return "0";
            }
            string z = null;
            stack a = new stack();
            int i = 0, j = 0, l = x.length;
            long tong = 0;
            while (i < l)
            {
                a.push(todec(convert.tostring(x[i])));
                i++;
            }
            while (a.count != 0)
            {
                tong = tong + convert.toint64(a.pop())*pow(16, j);
                j++;
            }
            z = convert.tostring(tong);
            return z;
        }

        #endregion //helperfunctions

        /// <summary>
        /// 
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        private static long pow(long x, long y)
        {
            int i = 1;
            long x = x;
            if (y == 0)
                return 1;
            while (i < y)
            {
                x = x*x;
                i++;
            }
            return x;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        private static string todec(string x)
        {
            switch (x)
            {
                case "a":
                    return "10";
                case "b":
                    return "11";
                case "c":
                    return "12";
                case "d":
                    return "13";
                case "e":
                    return "14";
                case "f":
                    return "15";
                default:
                    return x;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        private static string tohex(string x)
        {
            switch (x)
            {
                case "10":
                    return "a";
                case "11":
                    return "b";
                case "12":
                    return "c";
                case "13":
                    return "d";
                case "14":
                    return "e";
                case "15":
                    return "f";
                default:
                    return x;
            }
        }

        /// <summary>
        /// 将16进制byte数组转换成16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string tohexstring(byte[] bytes) // 0xae00cf => "ae00cf "
        {
            string hexstring = string.empty;
            if (bytes != null)
            {
                stringbuilder strb = new stringbuilder();

                for (int i = 0; i < bytes.length; i++)
                {
                    strb.append(bytes[i].tostring("x2"));
                }
                hexstring = strb.tostring();
            }
            return hexstring;
        }

 

/// <summary>
        /// 
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="ilength"></param>
        /// <returns></returns>
        public static string tohexstring(byte[] bytes, int ilength) // 0xae00cf => "ae00cf "
        {
            string hexstring = string.empty;
            if (bytes != null)
            {
                stringbuilder strb = new stringbuilder();

                if (bytes.length < ilength)
                {
                    ilength = bytes.length;
                }

                for (int i = 0; i < ilength; i++)
                {
                    strb.append(bytes[i].tostring("x2"));
                }
                hexstring = strb.tostring();
            }
            return hexstring;
        }

        /// <summary>
        /// 将byte数组转换为16进制字符串
        /// </summary>
        /// <param name="bytes">要转换的数组</param>
        /// <param name="istart">数组下标</param>
        /// <param name="ilength">长度</param>
        /// <returns></returns>
        public static string tohexstring(byte[] bytes, int istart, int ilength) // 0xae00cf => "ae00cf "
        {
            string hexstring = string.empty;
            if (bytes != null)
            {
                stringbuilder strb = new stringbuilder();

                //缓冲区长度问题,需清空缓冲区
                if (bytes.length < (ilength + istart))
                {
                    ilength = bytes.length;
                }

                for (int i = istart; i < ilength + istart; i++)
                {
                    strb.append(bytes[i].tostring("x2"));
                }
                hexstring = strb.tostring();
            }
            return hexstring;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="hexstring"></param>
        /// <param name="discarded"></param>
        /// <returns></returns>
        public static byte[] getbytes(string hexstring, out int discarded)
        {
            discarded = 0;
            string newstring = "";
            char c;
            // remove all none a-f, 0-9, characters
            for (int i = 0; i < hexstring.length; i++)
            {
                c = hexstring[i];
                if (uri.ishexdigit(c))
                    newstring += c;
                else
                    discarded++;
            }
            // if odd number of characters, discard last character
            if (newstring.length%2 != 0)
            {
                discarded++;
                newstring = newstring.substring(0, newstring.length - 1);
            }

            return hextobyte(newstring);
        }

        /// <summary>
        /// converts from binary coded decimal to integer
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static uint bcdtodec(uint num)
        {
            return hornerscheme(num, 0x10, 10);
        }

        /// <summary>
        /// converts from integer to binary coded decimal
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static uint dectobcd(uint num)
        {
            return hornerscheme(num, 10, 0x10);
        }

        private static uint hornerscheme(uint num, uint divider, uint factor)
        {
            uint remainder = 0, quotient = 0, result = 0;
            remainder = num%divider;
            quotient = num/divider;
            if (!(quotient == 0 && remainder == 0))
                result += hornerscheme(quotient, divider, factor)*factor + remainder;
            return result;
        }

        /// <summary>
        /// byte数组尾部0截取函数
        /// </summary>
        /// <param name="buf">原始byte数组</param>
        /// <param name="ilength">要截取的长度</param>
        /// <returns>截取后的数组</returns>
        public static byte[] interceptbyte(byte[] buf, int ilength)
        {
            stringbuilder sb = new stringbuilder(ilength*2);
            sb = sb.append(tohexstring(buf, (short) ilength));
            int discarded = 0;
            byte[] breturn = getbytes(sb.tostring(), out discarded);

            if (discarded > 0)
            {
                throw new exception("byte数组截取有数据丢失!");
            }
            return breturn;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="hexstring"></param>
        /// <returns></returns>
        public static byte[] hextobyte(string hexstring)
        {
            if (string.isnullorempty(hexstring))
            {
                hexstring = "00";
            }
            byte[] returnbytes = new byte[hexstring.length/2];
            for (int i = 0; i < returnbytes.length; i++)
                returnbytes[i] = convert.tobyte(hexstring.substring(i*2, 2), 16);
            return returnbytes;
        }

        /// <summary>
        /// 日期转bcd数组
        /// </summary>
        /// <param name="datetime"></param>
        /// <param name="type">4 6 7</param>
        /// <returns></returns>
        public static byte[] datetimetobcd(datetime datetime, ushort type)
        {
            string strservertime = string.format("{0:yyyymmddhhmmss}", datetime);

            byte[] bcd = new byte[type];
            if (type == 4)
            {
                bcd[0] = byte.parse(dectobcd(uint.parse(strservertime.substring(0, 2))).tostring("d2"));
                bcd[1] = byte.parse(dectobcd(uint.parse(strservertime.substring(2, 2))).tostring("d2"));
                bcd[2] = byte.parse(dectobcd(uint.parse(strservertime.substring(4, 2))).tostring("d2"));
                bcd[3] = byte.parse(dectobcd(uint.parse(strservertime.substring(6, 2))).tostring("d2"));
            }
            if (type == 6)
            {
                bcd[0] = byte.parse(dectobcd(uint.parse(strservertime.substring(2, 2))).tostring("d2"));
                bcd[1] = byte.parse(dectobcd(uint.parse(strservertime.substring(4, 2))).tostring("d2"));
                bcd[2] = byte.parse(dectobcd(uint.parse(strservertime.substring(6, 2))).tostring("d2"));
                bcd[3] = byte.parse(dectobcd(uint.parse(strservertime.substring(8, 2))).tostring("d2"));
                bcd[4] = byte.parse(dectobcd(uint.parse(strservertime.substring(10, 2))).tostring("d2"));
                bcd[5] = byte.parse(dectobcd(uint.parse(strservertime.substring(12, 2))).tostring("d2"));
            }
            if (type == 7)
            {
                bcd[0] = byte.parse(dectobcd(uint.parse(strservertime.substring(0, 2))).tostring("d2"));
                bcd[1] = byte.parse(dectobcd(uint.parse(strservertime.substring(2, 2))).tostring("d2"));
                bcd[2] = byte.parse(dectobcd(uint.parse(strservertime.substring(4, 2))).tostring("d2"));
                bcd[3] = byte.parse(dectobcd(uint.parse(strservertime.substring(6, 2))).tostring("d2"));
                bcd[4] = byte.parse(dectobcd(uint.parse(strservertime.substring(8, 2))).tostring("d2"));
                bcd[5] = byte.parse(dectobcd(uint.parse(strservertime.substring(10, 2))).tostring("d2"));
                bcd[5] = byte.parse(dectobcd(uint.parse(strservertime.substring(12, 2))).tostring("d2"));
            }
            return bcd;
        }

        /// <summary>
        /// bcd时间转日期时间
        /// </summary>
        /// <param name="bcdtime"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static datetime bcdtodatetime(byte[] bcdtime, ushort type)
        {
            stringbuilder sb = new stringbuilder();
            if (type == 4) //4位bcd码的日期
            {
                sb.append(bcdtodec(bcdtime[0]).tostring("d2"));
                sb.append(bcdtodec(bcdtime[1]).tostring("d2"));
                sb.append('-' + bcdtodec(bcdtime[2]).tostring("d2"));
                sb.append('-' + bcdtodec(bcdtime[3]).tostring("d2") + " ");
            }
            if (type == 6) //6位bcd码的时间
            {
                sb.append(datetime.now.tostring("yyyy").substring(0, 2));
                sb.append(bcdtodec(bcdtime[0]).tostring("d2"));
                sb.append('-' + bcdtodec(bcdtime[1]).tostring("d2"));
                sb.append('-' + bcdtodec(bcdtime[2]).tostring("d2") + " ");
                sb.append(bcdtodec(bcdtime[3]).tostring("d2") + ":");
                sb.append(bcdtodec(bcdtime[4]).tostring("d2") + ":");
                sb.append(bcdtodec(bcdtime[5]));
            }
            if (type == 7) //7位bcd码的日期
            {
                sb.append(bcdtodec(bcdtime[0]).tostring("d2"));
                sb.append(bcdtodec(bcdtime[1]).tostring("d2"));
                sb.append('-' + bcdtodec(bcdtime[2]).tostring("d2"));
                sb.append('-' + bcdtodec(bcdtime[3]).tostring("d2") + " ");
                sb.append(bcdtodec(bcdtime[4]).tostring("d2") + ":");
                sb.append(bcdtodec(bcdtime[5]).tostring("d2") + ":");
                sb.append(bcdtodec(bcdtime[6]));
            }

            datetime dt;
            //2011-3-26 当日期出错时的处理
            datetime.tryparse(sb.tostring(), out dt);

            return dt;
        }
    }
}