Click here to Skip to main content
14,668,312 members
Rate this:
Please Sign up or sign in to vote.
See more:
I know that this is going to be easy but I just cannot see it.

I have a string, thus "100A".

This has two CORRECT values for two bytes in it. No conversion is needed.

All I want to do is go from this string, to two bytes, i.e.

MSB = 0x10
LSB = 0x0A

And that's it.

Richard MacCutchan 15-Apr-15 10:46am
That makes no sense. If you inspect the content of that string in bytes it will be:
0x00,0x31, 0x00, 0x30, 0x00, 0x30, 0x00, 0x41. However if you want to use it to represent a hex value then you need to write a converter that can handle all hex values; not too difficult to figure out.
Sergey Alexandrovich Kryukov 15-Apr-15 10:57am
Well, it makes certain sense (perhaps not very practical). The input string could represent ushort value in hexadecimal form, which could be parsed. Please see Solution 1. You are right, not too difficult... :-)

Rate this:
Please Sign up or sign in to vote.

Solution 1

This is how:[^].

No, I was just kidding. :-)

This is one of the ways: use ushort.TryParse with System.Globalization.NumberStyles.HexNumber and neutral culture:[^],[^].

If TryParse returns true, the parsing was successful, if not, input data was in wrong format. In case of success, you got two bytes in one 16-bit value. To split it to separate bytes, you can use the class System.BitConverter:[^],[^].

Simple, isn't it?

One alternative: from your original string, extract two two-character sub-strings representing separate bytes, and use byte.TryParse in the same way.

Rate this:
Please Sign up or sign in to vote.

Solution 2

I knew it was easy. I did get the solution yesterday, but for some reason I simply didn't "see" it. Bad day. Anyway, it's just this:

string value = "100A";

// Convert to byte, telling converter the base to work in.
byte msb = Convert.ToByte(value.Substring(0, 2), 16);
byte lsb = Convert.ToByte(value.Substring(2, 2), 16);

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100