Convert from string ascii to string Hex

前端 未结 7 1086
既然无缘
既然无缘 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:41

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

提交回复
热议问题