Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String literal to byte

I am making a forms application is Visual C#. I have a textbox where a user must enter a number and a uppercase letter, example "9D".

What I need to do is put that letter into a byte array as a byte...so in my byte array it would:

array[index] = 0x9D

I know that the textbox class represents the 9D as a string. I am confused on how to make it into a literal byte (9D) and stick it in the array.

New to .Net so any help would be appreciated. I've looked at the System.Convert class and don't see anything I can use.

like image 720
brazc0re Avatar asked Dec 08 '11 18:12

brazc0re


People also ask

How do you convert strings to bytes?

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument.

What is a byte string literal?

Byte and byte string literals A byte literal is a single ASCII character (in the U+0000 to U+007F range) or a single escape preceded by the characters U+0062 ( b ) and U+0027 (single-quote), and followed by the character U+0027 .

How many bytes is a string?

But what about a string? A string is composed of: An 8-byte object header (4-byte SyncBlock and a 4-byte type descriptor)


3 Answers

Use Byte.Parse(string, NumberStyles):

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

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

like image 88
jason Avatar answered Sep 19 '22 10:09

jason


If you wanted it done a little faster and to allow '0x' in front of the number you can use Convert.ToByte("0x9D", 16). In my limited testing, Convert.ToByte was twice as fast as Byte.Parse

You can also validate the input with a simple Regex. This way you know the string will parse before calling any method to parse or convert it.

// 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}$")

Test code:

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;
like image 20
pstrjds Avatar answered Sep 17 '22 10:09

pstrjds


Use Byte.Parse to parse a string into a Byte.

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

Note that having the prefix 0x will cause a parse fail, so you may want to strip it out if it exists.

like image 41
Oded Avatar answered Sep 18 '22 10:09

Oded