C# 16进制(hex)字符串到字节流的转换 示例

在工程实践中,经常会将一些字节信息转换为16进制字符串,以便传递和分享,比如加密密钥信息。在这里提供一段转化示例, 以供交流学习。

将16进制字符串转化为 字节流

        public static byte[] HexStringToBytes(string hexStr)
        {
            if (string.IsNullOrEmpty(hexStr))
            {
                return new byte[0];
            }

            if (hexStr.StartsWith("0x"))
            {
                hexStr = hexStr.Remove(0, 2);
            }

            var count = hexStr.Length;

            if (count % 2 == 1)
            {
                throw new ArgumentException("Invalid length of bytes:" + count);
            }

            var byteCount = count / 2;
            var result = new byte[byteCount];
            for (int ii = 0; ii < byteCount; ++ii)
            {
                var tempBytes = Byte.Parse(hexStr.Substring(2 * ii,  2), System.Globalization.NumberStyles.HexNumber);
                result[ii] = tempBytes;
            }

            return result;
        }

将字节流转化为16进制字符串

        public static string BytesTohexString(byte[] bytes)
        {
            if (bytes == null || bytes.Count() < 1)
            {
                return string.Empty;
            }

            var count = bytes.Count();

            var cache = new StringBuilder();
            cache.Append("0x");
            for (int ii = 0; ii < count; ++ii)
            {
                var tempHex = Convert.ToString(bytes[ii], 16).ToUpper();
                cache.Append(tempHex.Length == 1 ? "0" + tempHex : tempHex);
            }

            return cache.ToString();
        }
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中,可以使用BitConverter类来将十六进制字符串转换为字节数组。首先,我们需要将十六进制字符串转换为字节数组,然后再将字节数组转换为十六进制字符串表示。下面是一个示例代码: ```csharp string hexString = "3132333435363738393a3b3c3d3e3f40"; byte[] byteArray = new byte = Convert.ToByte(hexString.Substring(i, 2), 16); } string result = BitConverter.ToString(byteArray).Replace("-", ""); Console.WriteLine(result); ``` 在上面的代码中,我们首先定义了一个十六进制字符串hexString。然后,我们创建了一个与十六进制字符串长度一半大小的字节数组byteArray。接下来,使用一个循环将每两个字符转换为一个字节,并将其存储到字节数组中。最后,使用BitConverter.ToString方法将字节数组转换为十六进制字符串表示,并使用Replace方法去除其中的分隔符“-”。最终,将转换后的结果打印出来。 注意,上述代码中的hexString长度必须为偶数,否则会引发异常。另外,如果需要将转换后的字节数组以其他形式使用,可以根据具体需求进行进一步操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [16进制字符串转字节字节数组](https://blog.csdn.net/weixin_28289089/article/details/117018463)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值