2017-10-20 1 views
-1

저는 현재 C# 프로그래밍에 초보자입니다. stackoverflow에서 16 진수를 바이트 배열로 변환하는 방법을 찾았지만 콘솔에 인쇄 할 때 알 수없는 몇 가지 이유 때문에 System.Byte[]과 같은 것을 얻을 수 있습니다. 해당 바이트 배열의 값을 어떻게 인쇄 할 수 있습니까?C# 16 진수를 읽고이를 바이트로 변환 한 다음 인쇄하십시오.

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()'을 사용하여 적절한 문자열을 생성하는 것입니다. 값을 16 진수 또는 10 진수로 인쇄할지 여부는 명확하지 않습니다. 말 그대로, 배열에서 값을 출력하는 방법에 대해 혼란스러워하는 것 같습니다. 예 : –

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

테스트를. (경우에 배열)을 수집을 인쇄 할 때하는 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)}]");  

결과에 Concat 또는 Join 항목을 잊지 마십시오 :

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- format-1-2-3-4-5-with-string-join-in-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 
관련 문제