C# 从字符串 ascii 转换为字符串 Hex

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15920741/
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 18:27:33  来源:igfitidea点击:

Convert from string ascii to string Hex

c#stringhexascii

提问by cheziHoyzer

Suppose I have this string

假设我有这个字符串

string str = "1234"

I need a function that convert this string to this string:

我需要一个将此字符串转换为该字符串的函数:

"0x31 0x32 0x33 0x34"  

I searched online and found a lot of similar things, but not an answer to this question.

我在网上搜索,发现了很多类似的东西,但没有回答这个问题。

采纳答案by internals-in

string str = "1234";
char[] charValues = str.ToCharArray();
string hexOutput="";
foreach (char _eachChar in charValues )
{
    // Get the integral value of the character.
    int value = Convert.ToInt32(_eachChar);
    // Convert the decimal value to a hexadecimal value in string form.
    hexOutput += String.Format("{0:X}", value);
    // to make output as your eg 
    //  hexOutput +=" "+ String.Format("{0:X}", value);

}

    //here is the HEX hexOutput 
    //use hexOutput 

回答by Davut Gürbüz

 [TestMethod]
    public void ToHex()
    {
        string str = "1234A";
        var result = str.Select(s =>  string.Format("0x{0:X2}", ((byte)s)));

       foreach (var item in result)
       {
           Debug.WriteLine(item);
       }

    }

回答by Davin Tryon

This is one I've used:

这是我用过的:

private static string ConvertToHex(byte[] bytes)
        {
            var builder = new StringBuilder();

            var hexCharacters = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

            for (var i = 0; i < bytes.Length; i++)
            {
                int firstValue = (bytes[i] >> 4) & 0x0F;
                int secondValue = bytes[i] & 0x0F;

                char firstCharacter = hexCharacters[firstValue];
                char secondCharacter = hexCharacters[secondValue];

                builder.Append("0x");
                builder.Append(firstCharacter);
                builder.Append(secondCharacter);
                builder.Append(' ');
            }

            return builder.ToString().Trim(' ');
        }

And then used like:

然后像这样使用:

string test = "1234";
ConvertToHex(Encoding.UTF8.GetBytes(test));

回答by Soner G?nül

static void Main(string[] args)
{
    string str = "1234";
    char[] array = str.ToCharArray();
    string final = "";
    foreach (var i in array)
    {
        string hex = String.Format("{0:X}", Convert.ToInt32(i));
        final += hex.Insert(0, "0X") + " ";       
    }
    final = final.TrimEnd();
    Console.WriteLine(final);
}

Output will be;

输出将是;

0X31 0X32 0X33 0X34

Here is a DEMO.

这是一个DEMO.

回答by Steve

This seems the job for an extension method

这似乎是扩展方法的工作

void Main()
{
    string test = "ABCD1234";
    string result = test.ToHex();
}

public static class StringExtensions
{
    public static string ToHex(this string input)
    {
        StringBuilder sb = new StringBuilder();
        foreach(char c in input)
            sb.AppendFormat("0x{0:X2} ", (int)c);
        return sb.ToString().Trim();
    }
}

A few tips.
Do not use string concatenation. Strings are immutable and thus every time you concatenate a string a new one is created. (Pressure on memory usage and fragmentation) A StringBuilder is generally more efficient for this case.

一些提示。
不要使用字符串连接。字符串是不可变的,因此每次连接一个字符串时都会创建一个新字符串。(内存使用和碎片压力)在这种情况下,StringBuilder 通常更有效。

Strings are array of characters and using a foreach on a string already gives access to the character array

字符串是字符数组,在字符串上使用 foreach 已经可以访问字符数组

These common codes are well suited for an extension method included in a utility library always available for your projects (code reuse)

这些通用代码非常适合包含在您的项目始终可用的实用程序库中的扩展方法(代码重用)

回答by JohnnyNoBrakes

Convert to byte array and then to hex

转换为字节数组,然后转换为十六进制

        string data = "1234";

        // Convert to byte array
        byte[] retval = System.Text.Encoding.ASCII.GetBytes(data);

        // Convert to hex and add "0x"
        data =  "0x" + BitConverter.ToString(retval).Replace("-", " 0x");

        System.Diagnostics.Debug.WriteLine(data);

回答by Laurynas Lazauskas

A nice declarative way to solve this would be:

解决这个问题的一个很好的声明式方法是:

var str = "1234"

string.Join(" ", str.Select(c => $"0x{(int)c:X}"))

// Outputs "0x31 0x32 0x33 0x34"