I hope this is allowed but I get exception in the attached code that I cannot solve.
The code fails in the same way using TinyCLR 1.0.0 or using a VS ConsoleApp.
Lots of folks in here WAY smarter than I.
Where did I go wrong?
I want to use hex strings for a TinyCLR serial app.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string shex = MakeHexString("Will George");
string utf8 = TextFromHexString(shex);
string MakeHexString(string str)
{
var sb = new StringBuilder();
var bytes = Encoding.UTF8.GetBytes(str);
foreach (var x in bytes)
{
sb.Append(x.ToString("X2"));
}
// returns {57696C6C2047656F726765}
return sb.ToString();
} //End MakeHexString
string TextFromHexString(string hexString)
{
Console.WriteLine("hexString = " + hexString);
var bytes = new byte[hexString.Length / 2];
var bytestemp = new byte();
// Will George
// "57696C6C2047656F726765"
// "57 69 6C 6C 20 47 65 6F 72 67 65" [22 bytes] //Fails at first 6C
for (var i = 0; i < bytes.Length; i++)
{
string test = hexString.Substring(i * 2, 2);
Console.WriteLine("test = " + test);
// The following line
// System.FormatException:
'Input string was not in a correct format.'
// However the first two bytes do not give this exception <<<<<
bytestemp = Convert.ToByte(test);
Console.WriteLine("bytestemp = " + bytestemp);
bytes[i] = bytestemp;
Console.WriteLine(bytes[i] + " i= " + i);
}
//
return Encoding.UTF8.GetString(bytes);
} //End TextFromHexString
} //main
} //class
} //namespace
Any comments? Thanks!