53 lines
No EOL
1.6 KiB
C#
53 lines
No EOL
1.6 KiB
C#
using System.Text;
|
|
using System.Linq;
|
|
|
|
namespace lib;
|
|
|
|
public static class Utils {
|
|
public static byte[] NumberToBytes(string Number) {
|
|
if(Number.Any(c => !char.IsDigit(c)) || Number.Length > 16) {
|
|
throw new Exception("Invalid arguments!");
|
|
}
|
|
byte[] res = Enumerable.Repeat((byte)0b1111_1111, 8).ToArray();
|
|
// Pad Number if needed to be of even length (because each 2 digits are turned into 1 byte)
|
|
Number = Number.Length % 2 == 0 ? Number : Number + '-';
|
|
|
|
for(int i = 0; i < Number.Length - 1; i += 2) {
|
|
char c1 = Number[i];
|
|
char c2 = Number[i + 1];
|
|
res[i / 2] = (byte)((DigitToByte(c1) << 4) | DigitToByte(c2));
|
|
}
|
|
return res;
|
|
}
|
|
|
|
public static string BytesToNumber(byte[] Bytes) {
|
|
string s = "";
|
|
foreach(byte b in Bytes) {
|
|
byte b1 = (byte)((b >> 4) & 0b1111);
|
|
byte b2 = (byte)(b & 0b1111);
|
|
s = s + ByteToDigit(b1) + ByteToDigit(b2);
|
|
}
|
|
return new string(s.Where(c => char.IsDigit(c)).ToArray());
|
|
}
|
|
|
|
|
|
public static byte DigitToByte(char c) {
|
|
if (int.TryParse(c.ToString(), out int d)) {
|
|
return (byte)d;
|
|
}
|
|
else {
|
|
return 0b1111; // empty, turned into '-' later to be discarded
|
|
}
|
|
}
|
|
|
|
public static char ByteToDigit(byte b) {
|
|
byte offset = Encoding.ASCII.GetBytes("0")[0];
|
|
|
|
if(b == 0b1111) {
|
|
return '-';
|
|
}
|
|
else {
|
|
return Encoding.ASCII.GetChars([(byte)(b + offset)])[0];
|
|
}
|
|
}
|
|
} |