.NET Convert from string of Hex values into Unicode characters (Support different code pages)

后端 未结 2 778
时光说笑
时光说笑 2020-12-19 15:01

I have a string of Hex values...

String hexString = \"8A65\";

I need to convert this string into their Unicode equivalents. The tricky part

相关标签:
2条回答
  • 2020-12-19 15:45
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;
    
    class Sample {
        static public void Main(){
            var data = "8A65";
            Regex regex = new Regex(@"(?<hex>[0-9A-F]{2})",RegexOptions.IgnoreCase | RegexOptions.Compiled);
            byte[] bytes = regex.Matches(data).OfType<Match>().Select(m => Convert.ToByte(m.Groups["hex"].Value,16)).ToArray();
            char[] chars = Encoding.GetEncoding(932).GetChars(bytes);
            Console.WriteLine(new String(chars));
       }
    } 
    
    0 讨论(0)
  • 2020-12-19 15:57

    You need to convert the hex string to bytes (see SO post). Passing the hex string into one of the encodings to convert it to bytes just gives you the byte equivalent of those characters. I am assuming what you want is the two bytes that the 4 character string represents, so decode the hex to bytes and then you can use the encoding on the decoded bytes to get back a string.

    Encoding.{YourEncoding}.GetChars(hexBytes);
    
    0 讨论(0)
提交回复
热议问题