Convert string to hex-string in C#

后端 未结 5 824
说谎
说谎 2020-11-28 06:10

I have a string like \"sample\". I want to get a string of it in hex format; like this:

  \"796173767265\"

Please give the

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 06:33

    For Unicode support:

    public class HexadecimalEncoding
    {
        public static string ToHexString(string str)
        {
            var sb = new StringBuilder();
    
            var bytes = Encoding.Unicode.GetBytes(str);
            foreach (var t in bytes)
            {
                sb.Append(t.ToString("X2"));
            }
    
            return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
        }
    
        public static string FromHexString(string hexString)
        {
            var bytes = new byte[hexString.Length / 2];
            for (var i = 0; i < bytes.Length; i++)
            {
                bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            }
    
            return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
        }
    }
    

提交回复
热议问题