Cosmos/source/Cosmos.Common/ByteToString.cs
Elia Sulimanov 9e185e27b2 Added new check on the string passed to StrToByteArray
StrToByteArray had unsafe, unchecked case in which str in not in a number format.
Passing non-numerical string to byte.Parse makes it throw the "System.FormatException: Input string was not in a correct format." exception.

Added new condition, to check if the string passed to this function is numeric, in order to prevent unhandled exception problem.
2020-05-28 01:46:28 +03:00

45 lines
1.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Text;
namespace Cosmos.Common
{
static public class ByteToString
{
public static byte[] StrToByteArray(string str)
{
if (str.Length == 0 || !StringHelper.IsNumeric(str))
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;
}
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;
}
}
}