从字符串中获取字节 [英] Get bytes from string
本文介绍了从字符串中获取字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这很容易但是我看不到它。
我有一个字符串,因此100A。
它有两个CORRECT值,包含两个字节。不需要转换。
我想做的就是从这个字符串转到两个字节,即
MSB = 0x10
LSB = 0x0A
就是这样。
谢谢。
解决方案
这是如何: https://msdn.microsoft.com/en-us/library/ds4kkd55(v = vs.110).aspx [ ^ ]。
不,我只是在开玩笑。 :-)
这是其中一种方法:使用ushort.TryParse
与System.Globalization.NumberStyles.HexNumber
和中性文化:
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 [ ^ ]。
如果TryParse
返回true,解析成功,否则输入数据格式错误。如果成功,您在一个16位值中有两个字节。要将其拆分为单独的字节,您可以使用类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 [ ^ ]。
简单,不是吗?
一种替代方法:从原始字符串中提取两个代表单独字节的双字符子字符串,然后使用byte.TryParse
以同样的方式。
-SA
我知道它是简单。我昨天确实得到了解决方案,但出于某种原因我根本没有看到它。糟糕的一天。无论如何,就是这样:
string value = 100A;
// 转换为字节,告诉转换器基础工作。
byte msb = Convert.ToByte( value .Substring( 0 , 2 ), 16 );
byte lsb = Convert.ToByte( value .Substring( 2 , 2 ), 16 );
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.
解决方案
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: useushort.TryParse
withSystem.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[^].
IfTryParse
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 classSystem.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 usebyte.TryParse
in the same way.
—SA
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);
这篇关于从字符串中获取字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文