簡體   English   中英

從字符串 ascii 轉換為字符串 Hex

[英]Convert from string ascii to string Hex

假設我有這個字符串

string str = "1234"

我需要一個將此字符串轉換為該字符串的函數:

"0x31 0x32 0x33 0x34"  

我在網上搜索,發現了很多類似的東西,但沒有回答這個問題。

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 

這似乎是擴展方法的工作

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();
    }
}

一些提示。
不要使用字符串連接。 字符串是不可變的,因此每次連接一個字符串時都會創建一個新字符串。 (內存使用和碎片壓力)在這種情況下,StringBuilder 通常更有效。

字符串是字符數組,在字符串上使用 foreach 已經可以訪問字符數組

這些通用代碼非常適合包含在您的項目始終可用的實用程序庫中的擴展方法(代碼重用)

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);
}

輸出將是;

0X31 0X32 0X33 0X34

這是一個DEMO

轉換為字節數組,然后轉換為十六進制

        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);

解決這個問題的一個很好的聲明式方法是:

var str = "1234"

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

// Outputs "0x31 0x32 0x33 0x34"
 [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);
       }

    }

這是我用過的:

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(' ');
        }

然后像這樣使用:

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

        // 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");

        richTextBox1.Text = data;

如果要更改“ 0x”或完全刪除間距,只需編輯或刪除以下內容:

data = "0x" + BitConverter.ToString(retval).Replace("-", " 0x");

這幾乎適用於所有內容(從按鈕到菜單欄。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM