c# 字符串与16进制互导

参考链接:
c#实现16进制和字符串之间转换的代码
C#字符串与16进制的相互转换
结果:
在这里插入图片描述
code:

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

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"F:\mrm\publicShare\thumbnails";
            var directory = Directory.GetFiles(path);

            foreach (var s in directory)
            {
                string name = Path.GetFileNameWithoutExtension(s);
                var hex = StringToHex(name);
                var str = HexStringToBytes(hex);

                Console.WriteLine(hex);
                Console.WriteLine(Encoding.GetEncoding("GB2312").GetString(str));
            }

            Console.Read();
        }

        public static string StringToHex(string s)
        {
            var b = Encoding.Default.GetBytes(s);
            string result = string.Empty;
            for (int i = 0; i < b.Length; i++)
            {
                result += Convert.ToString(b[i], 16);
            }

            return result;
        }

        public static byte[] HexStringToBytes(string s)
        {
            s = s.Replace(" ", "").Trim().ToUpper();
            byte[] buffer = new byte[s.Length/2];
            for (int i = 0; i < s.Length; i+=2)
            {
                buffer[i / 2] = (byte) Convert.ToByte(s.Substring(i, 2), 16);
            }

            return buffer;
        }
    }
}

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页