forked from CosmosOS/Cosmos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ByteToString.cs
60 lines (57 loc) · 2.01 KB
/
ByteToString.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Collections.Generic;
using System.Text;
namespace Cosmos.Common
{
/// <summary>
/// Helper class for converting byte array to string and vice versa.
/// </summary>
static public class ByteToString
{
/// <summary>
/// Parse numeric (positive) string to byte array.
/// </summary>
/// <param name="str">A string to be converted to byte array.</param>
/// <exception cref="Exception">thrown when the passed string length is 0, string length is not divisible by 3 or the string not numeric</exception>
/// <returns>Byte array.</returns>
public static byte[] StrToByteArray(string str)
{
if (str.Length == 0 || !StringHelper.IsNumeric(str) || str.Length % 3 != 0)
throw new Exception("Invalid string value in StrToByteArray");
byte val;
byte[] byteArr = new byte[str.Length / 3];
int i = 0;
int j = 0;
do
{
val = byte.Parse(str.Substring(i, 3));
byteArr[j++] = val;
i += 3;
}
while (i < str.Length);
return byteArr;
}
/// <summary>
/// Parse byte array to string.
/// To be used on byte arrays created by StrToByteArray method.
/// </summary>
/// <param name="byteArr">A byte array to be converted to string.</param>
/// <returns>String value.</returns>
public static string ByteArrToString(byte[] byteArr)
{
byte val;
string tempStr = "";
for (int i = 0; i <= byteArr.GetUpperBound(0); i++)
{
val = byteArr[i];
if (val < (byte)10)
tempStr += "00" + val.ToString();
else if (val < (byte)100)
tempStr += "0" + val.ToString();
else
tempStr += val.ToString();
}
return tempStr;
}
}
}