C# 2進位、8進位、10進位、16進位...各種進位間的轉換(二)搜集的各種轉換及方法

来源:https://www.cnblogs.com/Tanghongchang/archive/2018/09/14/9646881.html
-Advertisement-
Play Games

/// /// 十進位轉換為二進位 /// /// /// 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") + "	   

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 執行後,輸出的結果為: ...
  • GitHub代碼鏈接 1.項目相關要求 •基本功能列表: -c 統計文件中字元的個數 -w 統計文件中的詞數 -l 統計文件中的行數 •拓展功能: -a 統計文件中代碼行數、註釋行數、空行 2.PSP2.1 PSP2.1 Personal Software Process Stages 預估耗時(小 ...
  • 在一個二維數組中(每個一維數組的長度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。 1.二維數組,行row從左到右遞增,列col從上到下遞增 2.定左下角為比較點,比它大的位於它右邊,因此c... ...
  • 簡單紹一下如何將ASP.NET Core 應用發佈到Linux (Ubuntu)伺服器上,都是文檔的東西。 伺服器結構 ASP.NET Core 2.x 有兩種server: HTTP.sys 只支持Windows,並支持一些Windows獨有的特性。 Kestrel,跨平臺的伺服器,高度優化,這個 ...
  • Github項目地址:https://github.com/3116005131/3116005131.git PSP2.1 Personal Software Process Stages 預估耗時(分鐘) 實際耗時(分鐘) Planning 計劃 · Estimate · 估計這個任務需要多少時 ...
  • 紙牌游戲有很多種玩法,C#代碼寫的紙牌游戲,網上也能找到不少,從中也能學習到不少知識,自己動手也寫一個,算是記錄下學習過程吧. 紙牌21點的玩法也比較簡單,就是看誰手中的所有牌相加是21點,或是離21點的數字最近,最大者贏.照著這樣思路開始編寫代碼. 牌面A到10按牌面數字算點數,J,Q,K,大小王 ...
  • 該文可參考我的另一篇關聯文章: https://www.cnblogs.com/lxhbky/p/6957825.html 配置如下: 轉換如下: //獲取外圍屬性的值: //獲取屬性對應的集合 ...
  • Cocos2d-x的控制項類型僅限於基礎的幾種,如label、button、listview等,做游戲開發時基本夠用了。但如果想用cocos2dx來做工具的話,那就有點困難了。 這裡介紹一個適合做工具的UI庫:ImGui, 地址:https://github.com/ocornut/imgui。核心文 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...