C# 16進位(十六進位)字串\xOO 和 字元陣列(ByteArray) 互轉

C# 16進位(十六進位)字串\xOO 和 字元陣列(ByteArray) 互轉

C# 16進位(十六進位)字串\xOO 和 字元陣列(ByteArray) 互轉


資料來源: chatgpt


\x00 -> byte [正則表達式]

    private byte[] Hex2ByteArray(string StrData)// \xOO -> byte
    {
        MatchCollection matches = Regex.Matches(StrData, @"\\x([0-9A-Fa-f]{2})");
        byte[] bytes = new byte[matches.Count];
        for (int i = 0; i < matches.Count; i++)
        {
            bytes[i] = Convert.ToByte(matches[i].Groups[1].Value, 16);
        }
        return bytes;
    }


byte -> \X00 [迴圈&字串相加]

    private string ByteArray2Hex(byte[] bytes)// byte -> \xOO
    {
        string strResult = "";
        foreach (byte b in bytes)
        {
            strResult += $"\\x{b:X2}";
        }
        return strResult;
    }

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *