String literal to byte

I am making a Visual C # forms application. I have a text box where the user must enter a number and an uppercase letter, for example "9D".

I need to make this letter into a byte array as a byte ... so in my byte array:

array[index] = 0x9D

I know that the textbox class represents 9D as a string. I am confused about how to turn it into a literal byte (9D) and insert it into an array.

New to .Net, so any help would be appreciated. I looked at the System.Convert class and see nothing that I can use.

+5
source share
3 answers

Use Byte.Parse(string, NumberStyles):

byte b = Byte.Parse(text, NumberStyles.HexNumber);

Or Byte.TryParse(string, NumberStyles, IFormatProvider, out Byte), to gracefully handle invalid input.

+6

"0x" , Convert.ToByte("0x9D", 16). Convert.ToByte , Byte.Parse

Regex. , , .

// Checks that the string is either 2 or 4 characters and contains only valid hex
var regex = new Regex(@"^(0x)*[a-fA-F\d]{2}$")

:

const int count = 100000;
var data = "9D";
var sw = new Stopwatch();
sw.Reset();

byte dest = 0;
sw.Start();
for(int i=0; i < count; ++i)
{
    dest = Byte.Parse(data, NumberStyles.AllowHexSpecifier);
}
sw.Stop();
var parseTime = sw.ElapsedMilliseconds;
sw.Reset();
sw.Start();
for(int i=0; i < count; ++i)
{
    dest = Convert.ToByte(data, 16);
}
sw.Stop();
var convertTime = sw.ElapsedMilliseconds;
+4

Use Byte.Parseto parse string in Byte.

array[index] = Byte.Parse("9D", NumberStyles.AllowHexSpecifier);

Note that having a prefix 0xwill cause parsing to fail, so you can remove it if it exists.

+1
source

All Articles