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

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 运行结果 

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

上一篇:BOS项目(SSH)03_04_登录功能--MD5加密、MD5加盐、EasyUI提示框和下拉菜单、登录退出功能、切换皮肤


下一篇:查找SHA1值