Convert from string ascii to string Hex

2020-06-01 07:21发布

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.

7条回答
迷人小祖宗
2楼-- · 2020-06-01 07:43
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 
查看更多
看我几分像从前
3楼-- · 2020-06-01 07:46

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"
查看更多
家丑人穷心不美
4楼-- · 2020-06-01 07:47
 [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);
       }

    }
查看更多
一夜七次
5楼-- · 2020-06-01 07:59

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));
查看更多
Anthone
6楼-- · 2020-06-01 08:00

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.

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

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

查看更多
Animai°情兽
7楼-- · 2020-06-01 08:02

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);
查看更多
登录 后发表回答