Convert from string ascii to string Hex

前端 未结 7 1090
既然无缘
既然无缘 2021-02-07 10:31

Suppose I have this string

string str = \"1234\"

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

\"0x31 0x32 0x33          


        
7条回答
  •  被撕碎了的回忆
    2021-02-07 10:40

    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)

提交回复
热议问题