C# byte[]转换为字符串

时间:2022-07-23
本文章向大家介绍C# byte[]转换为字符串,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] byt1 = { 0x01, 0x11, 0x21,0xff ,0b0001_0001,0b0001_1111};//定义并初始化8位无符号字节数组
            StringBuilder sNeed = new StringBuilder();
            foreach (var item in byt1)
                Console.Write(item + "**");//遍历并输出每个字节对应的十进制数值
            Console.WriteLine("r");
            Console.WriteLine(BitConverter.ToString(byt1));//将字节数组转换为字符串并输出
            Console.WriteLine(BitConverter.ToString(byt1).Replace("-",""));//去掉连接符
            sNeed.Append(BitConverter.ToString(byt1).Replace("-", ""));
            Console.WriteLine(sNeed.ToString());
            Console.WriteLine(BitConverter.ToString(strToToHexByte(sNeed.ToString())));
            Console.ReadKey();
        }

        private static byte[] strToToHexByte(string hexString)
        {
            hexString = hexString.Replace("-", "");
            if ((hexString.Length % 2) != 0)
                hexString += "20";
            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;
        }
    }
}