假设我有这个字符串
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 循环遍历字符串可以直接访问字符数组
这些常见代码适合作为扩展方法包含在一个实用程序库中,始终可用于您的项目(代码重用)
将其转换为字节数组,然后再转换为十六进制
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);
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
Here is a DEMO
.
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);
}
}
string.Format("0x{0:X2}", (int)s)
。原因:(1)X8
从未被使用,因为用于此参数的值是字符串。(2)char
可以包含超出字节范围的值。 - Daniel Hilgarth这是我用过的一个:
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
没有重载ToString
,可以接受类型为string
的参数。 - Daniel Hilgarth