c#-byte数组转换成16进制字符串和字符数组的方法

该代码示例展示了如何在C#中将字节数组转换为16进制字符串,以及如何将16进制字符串还原回字节数组。主要涉及基本的数据类型转换和字符串操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.概述

 returnStr += byteArray[i].ToString("X2");

byte[] returnBytes = new byte[hexString.Length / 2];

 returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);

2.代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp14
{
    class Program
    {
        static void Main(string[] args)
        {
            test1();
            test2();
            Console.ReadKey();
        }
        static void test1() {
            Console.WriteLine("字节数组 转 16进制字符串");
            byte[] byteArray = new byte[2];
            for (int i = 0; i < 2; i++)
            {
                byteArray[i] = 0xF0;
            }
            string str = byteTo16Str(byteArray);
            Console.WriteLine(str);
        }
        static void test2() {
            Console.WriteLine("16进制字符串 转 字节数组");
            string str16 = "f0fa";
            byte[] byteArray2 = StrToHexByte(str16);
            foreach(byte b in byteArray2) {
                Console.WriteLine(b);
            }
        }
        // 字节数组转16进制字符串 
        static string byteTo16Str(byte[] byteArray) {
            String returnStr = "";
            for (int i = 0; i < byteArray.Length; i++)
            {
                returnStr += byteArray[i].ToString("X2");

            }
            return returnStr;
        }
        // 将16进制的字符串转为byte[]
        public static byte[] StrToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            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;
        }
    }
}

3 运行结果 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值