在 C# 中将字符串转换为十六进制字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16999604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:19:05  来源:igfitidea点击:

Convert string to hex-string in C#

c#.netstringhex

提问by Dariush Jafari

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

我有一个像“sample”这样的字符串。我想以十六进制格式获取它的字符串;像这样:

  "796173767265"

Please give the C# syntax.

请给出 C# 语法。

采纳答案by Mike Perrenoud

First you'll need to get it into a byte[], so do this:

首先,您需要将其放入一个byte[],因此请执行以下操作:

byte[] ba = Encoding.Default.GetBytes("sample");

and then you can get the string:

然后你可以得到字符串:

var hexString = BitConverter.ToString(ba);

now, that's going to return a string with dashes (-) in it so you can then simply use this:

现在,这将返回一个带有破折号 ( -)的字符串,因此您可以简单地使用它:

hexString = hexString.Replace("-", "");

to get rid of those if you want.

如果你想摆脱那些。

NOTE:you could use a different Encodingif you needed to.

注意:Encoding如果需要,您可以使用不同的。

回答by Damith

var result = string.Join("", input.Select(c => ((int)c).ToString("X2")));

OR

或者

var result  =string.Join("", 
                input.Select(c=> String.Format("{0:X2}", Convert.ToInt32(c))));

回答by fubo

According to this snippet here, this approach should be good for long strings:

根据这里的这个片段,这种方法应该适用于长字符串:

private string StringToHex(string hexstring)
{
    StringBuilder sb = new StringBuilder();
    foreach (char t in hexstring)
    { 
        //Note: X for upper, x for lower case letters
        sb.Append(Convert.ToInt32(t).ToString("x")); 
    }
    return sb.ToString();
}

usage:

用法:

string result = StringToHex("Hello world"); //returns "48656c6c6f20776f726c64"


Another approach in one line

一行中的另一种方法

string input = "Hello world";
string result = String.Concat(input.Select(x => ((int)x).ToString("x")));

回答by franckspike

For Unicode support:

对于 Unicode 支持:

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"
    }
}

回答by Slai

few Unicode alternatives

少数 Unicode 替代品

var s = "0";

var s1 = string.Concat(s.Select(c => $"{(int)c:x4}"));  // left padded with 0 - "0030d835dfcfd835dfdad835dfe5d835dff0d835dffb"

var sL = BitConverter.ToString(Encoding.Unicode.GetBytes(s)).Replace("-", "");       // Little Endian "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
var sB = BitConverter.ToString(Encoding.BigEndianUnicode.GetBytes(s)).Replace("-", ""); // Big Endian "0030D835DFCFD835DFDAD835DFE5D835DFF0D835DFFB"

// no encodding "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
byte[] b = new byte[s.Length * sizeof(char)];
Buffer.BlockCopy(s.ToCharArray(), 0, b, 0, b.Length);
var sb = BitConverter.ToString(b).Replace("-", "");