Click here to Skip to main content
15,894,405 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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.

Thanks.
Posted
Comments
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... :-)
—SA

This is how: https://msdn.microsoft.com/en-us/library/ds4kkd55(v=vs.110).aspx[^].

No, I was just kidding. :-)

This is one of the ways: use ushort.TryParse with System.Globalization.NumberStyles.HexNumber and neutral culture:
https://msdn.microsoft.com/en-us/library/zfh885y3%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/system.globalization.numberstyles%28v=vs.110%29.aspx[^].

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:
https://msdn.microsoft.com/en-us/library/system.bitconverter%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/8wwsdz3k%28v=vs.110%29.aspx[^].

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.

—SA
 
Share this answer
 
v2
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:

C#
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);
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900