C# 16进制字符串与byte数组互转

这段代码提供了两个方法,一个将字节数组转换成16进制格式的字符串,另一个则将16进制格式的字符串转换回字节数组。还包括了一个校验16进制字符串的辅助函数,确保字符串的正确性。
 /// <summary>
        /// byte[]转16进制格式string
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ToHexString(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                { 
                    returnStr += bytes[i].ToString("X2") + " ";
                }
            }
            return returnStr;
        }
/// <summary>
        /// 字符串转16进制字节数组 
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] ToHexByteArray(string hexString)
        {
            hexString = CheakHexString(hexString);
            hexString = hexString.Replace(" ", "");
            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>
        /// 校验16进制字符串
        /// </summary>
        /// <param name="strBuffHex">16进制字符串</param>
        /// <returns></returns>
        private static string CheakHexString(string strBuffHex)
        {
            strBuffHex = strBuffHex.Trim();     //去除前后空字符
            strBuffHex = strBuffHex.Replace(',', ' ');  //去掉英文逗号
            strBuffHex = strBuffHex.Replace(',', ' '); //去掉中文逗号
            strBuffHex = strBuffHex.Replace("0x", "");  //去掉0x
            strBuffHex = strBuffHex.Replace("0X", "");  //去掉0X
            strBuffHex = Regex.Replace(Regex.Replace(strBuffHex, @"(?i)[^a-f\d\s]+", ""), "\\w{3,}", m => string.Join(" ", Regex.Split(m.Value, @"(?<=\G\w{2})(?!$)").Select(x => x.PadLeft(2, '0')).ToArray())).ToUpper();
            return strBuffHex;
        } 

### 将十六进制字符串换为字节数组的方法 在 C# 中,可以采用多种方法实现将十六进制字符串换为字节数组的功能。以下是几种常见的实现方式: #### 方法一:手动解析并逐字符处理 可以通过遍历输入的十六进制字符串,并将其每两个字符组合成一个字节来完成换。 ```csharp public static byte[] HexStringToByteArray(string hex) { if (hex.Length % 2 != 0) throw new ArgumentException("The binary key cannot have an odd number of digits."); var result = new byte[hex.Length / 2]; for (int i = 0; i < hex.Length; i += 2) { result[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); } return result; } ``` 这种方法适用于标准形式的连续十六进制字符串[^4]。 --- #### 方法二:基于 `Convert.ToByte` 的分隔符支持版本 如果十六进制字符串是以空格或其他分隔符分割的形式存在,则可以先拆分为子串再逐一换为字节。 ```csharp public static byte[] HexStringWithSpacesToByteArray(string hexString) { string[] parts = hexString.Split(' '); byte[] byteArray = new byte[parts.Length]; for (int i = 0; i < parts.Length; i++) { byteArray[i] = Convert.ToByte(parts[i], 16); } return byteArray; } ``` 此方法特别适合于带有空格分隔的十六进制数据流[^3]。 --- #### 方法三:利用正则表达式优化复杂场景下的匹配 对于可能包含非有效字符的情况,可借助正则表达式过滤掉非法部分后再执行换操作。 ```csharp using System.Text.RegularExpressions; public static byte[] SafeHexStringToByteArray(string input) { Regex regex = new Regex(@"\G[\da-f]{2}", RegexOptions.IgnoreCase | RegexOptions.Compiled); List<byte> bytes = new List<byte>(); foreach (Match match in regex.Matches(input)) { bytes.Add(Convert.ToByte(match.Value, 16)); } return bytes.ToArray(); } ``` 这种方式能够更灵活地应对不规则格式的数据源。 --- 以上三种方案均能有效地解决从不同类型的十六进制表示到实际内存存储单位——即字节数组间的映射需求。开发者可根据具体应用场景选择最合适的算法实现路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值