SW/C#
문자열16진수를 바이트 형태로 변환 / 특정 문자로 바이트 분리
또난
2020. 8. 8. 18:14
// 16진수 문자열형태를 16진수 바이트형태로 저장...
string str = "4D 42 43 52 47 30 30 36 30 30 39";
byte[] test = str.Split(' ').Select(s => Convert.ToByte(s, 16)).ToArray();
// ======== 바이트 분리 ====================
//MBCR
char[] splitId = { 'M', 'B', 'C', 'R' };
List<byte[]> result = new List<byte[]>();
int start = 0;
for (int i = 0; i < test.Length; i++)
{
if ((test[i] == splitId[0] && test[i+1] == splitId[1] && test[i + 2] == splitId[2] && test[i + 3] == splitId[3]) && i != 0)
{
//Console.WriteLine(start);
byte[] _in = new byte[i - start];
Array.Copy(test, start, _in, 0, i - start);
result.Add(_in);
start = i; // 여기에 splitId 갯수만큼 더하면 제외되어 분리된다.
}
else if ((test[i] == splitId[0] && test[i + 1] == splitId[1] && test[i + 2] == splitId[2] && test[i + 3] == splitId[3]) && i == 0)
{
start = i; // 여기에 splitId 갯수만큼 더하면 제외되어 분리된다.
}
else if (test.Length - 1 == i && i != start)
{
//Console.WriteLine(start);
byte[] _in = new byte[i - start + 1];
Array.Copy(test, start, _in, 0, i - start + 1);
result.Add(_in);
}
}
Console.WriteLine(result.Count);
// DisplayArrayValues(test, "test ", test.Length);
foreach(byte[] data in result)
{
DisplayArrayValues(data, "test1", data.Length);
}
public static void DisplayArrayValues(Array arr, string name, int len)
{
// Get the length of one element in the array.
int elementLength = Buffer.ByteLength(arr) / arr.Length;
string formatString = String.Format(" {{0:X{0}}}", 2 * elementLength);
Console.Write("{0}({1}) :", name, len);
for (int ctr = 0; ctr < len; ctr++)
Console.Write(formatString, arr.GetValue(ctr));
Console.WriteLine();
}
https://www.codeproject.com/Questions/500127/Howplustoplussplitplusbyteplusarray
[Solved] How to split byte array - CodeProject
www.codeproject.com