2017-10-20 132 views
-1

我目前对c#编程很新。在stackoverflow上,我发现这种将十六进制数字转换为字节数组的方式,但是由于某些未知原因,当我将其打印到控制台时,我得到类似System.Byte[]的东西。我怎样才能打印该字节数组的值?c#读取十六进制数并将其转换为字节,然后打印它

public static void Main(string[] args) 
    { 
     string hex = "010000015908178fd8000f0fcaf1209a953c006900dd0e0022000e050101f0015001150351220142375308c700000036f10000601a520000000053000069de54000000205500000387570d4a9e50640000006f0001"; 
     byte[] array = null; 
     array = Enumerable.Range(0, hex.Length) // Converts hex string to byte array or am I worng? 
         .Where(x => x % 2 == 0) 
         .Select(x => Convert.ToByte(hex.Substring(x, 2), 16)) 
         .ToArray(); 
     Console.WriteLine(array); 
    } 
+1

你提的问题是过于宽泛。根本不清楚你想如何打印数组的值。一种方法是打印原始的'hex'值。另一种方法是编写一个'foreach'来打印每个值。另一种方法是使用'string.Join()'来生成一个合适的字符串。目前还不清楚是否要以十六进制或十进制打印值。从字面上看,你似乎对如何从数组中打印值感到困惑。见例如标记为重复 –

+0

string.Join为我完美工作。谢谢! – CaL17

+0

重复的https://stackoverflow.com/questions/32694766/how-to-print-array-in-format-1-2-3-4-5-with-string-join-in-c以及https: //stackoverflow.com/questions/37663663/print-array-in-console-gives-system-int32。 –

回答

0

如果你喜欢的LINQ

string hex = "010000015908178fd8000f0fcaf1209a953c006900dd0e0022000e050101f0015001150351220142375308c700000036f10000601a520000000053000069de54000000205500000387570d4a9e50640000006f0001"; 

byte[] result = Enumerable 
    .Range(0, hex.Length/2) // The range should be hex.Length/2, not hex.Length 
    .Select(index => Convert.ToByte(hex.Substring(index * 2, 2), 16)) 
    .ToArray(); 

测试。当打印出集合(的情况下阵列),请不要忘了ConcatJoin项目为string

// Let's concat (no separator) result back to string and compare with the original 
string test = string.Concat(result.Select(b => b.ToString("x2"))); 

Console.WriteLine(test == hex ? "passed" : "failed"); 

// Let's print out the array (we join items with a separator - ", " in the case) 
Console.WriteLine($"[{string.Join(", ", result)}]");  

结果:

passed 
[1, 0, 0, 1, 89, 8, 23, 143, 216, 0, ... , 100, 0, 0, 0, 111, 0, 1]  
+0

我们已经有很多关于如何使用String.Join()来打印出数组的例子。如https://stackoverflow.com/questions/37663663/print-array-in-console-gives-system-int32和https://stackoverflow.com/questions/32694766/how-to-print-array-in-格式1-2-3-4-5,用串,加入在-C。你应该投票结束重复这个问题,而不是增加混乱。 –

0
如果你想打印出每

字节,你可以使用foreach,这是相应的代码。

foreach (byte bt in array) 
{ 
    Console.Write(bt+" "); 
} 

输出:

1 0 0 1 89 8 23 143 216 0 15 15 202 241 32 154 149 60 0 105 0 221 14 0 34 0 14 5 1 1 240 1 80 1 21 3 81 34 1 66 55 83 8 199 0 0 0 54 241 0 0 96 26 82 0 0 0 0 83 0 0 105 222 84 0 0 0 32 85 0 0 3 135 87 13 74 158 80 100 0 0 0 111 0 1 
相关问题