二进制字符串到整数
我有一个由用户输入的二进制字符串,我需要将其转换为整数。
起初,我天真地使用了这个简单的行:
Convert.ToInt32("11011",2);
不幸的是,如果用户直接输入整数,这会引发异常。
Convert.ToInt32("123",2); // throws Exception
如何确保用户输入的字符串确实是二进制字符串?
try..catch
Int32.TryParse
谢谢
I have a binary string, entered by the user, which I need to convert to an integer.
At first, I naively used this simple line:
Convert.ToInt32("11011",2);
Unfortunately, this throws an exception if the user enters the integer directly.
Convert.ToInt32("123",2); // throws Exception
How can I make sure that the string entered by the user actually is a binary string?
try..catch
Int32.TryParse
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
Regex
检查它是否为“^[01]+$”(或者更好的是“^[01]{1,32}$”),然后 使用转换
?当然,无论如何,异常不太可能是一个大问题! 不优雅? 或许。 但它们有效。
示例(针对垂直空间格式化):
You could use a
Regex
to check that it is "^[01]+$" (or better, "^[01]{1,32}$"), and then useConvert
?of course, exceptions are unlikely to be a huge problem anyway! Inelegant? maybe. But they work.
Example (formatted for vertical space):
感谢您的出色且快速的回答!
不幸的是,我的要求发生了变化。 现在用户几乎可以输入任何格式。 二进制、十进制、十六进制。 所以我决定 try - catch 只是提供最简单和最干净的解决方案。
因此,为了更好地衡量,我发布了我现在使用的代码。 我认为它非常清晰,甚至有些优雅,至少我是这么认为^^。
所以感谢鼓励我使用 try - catch,我认为它确实提高了我代码的可读性。
谢谢
Thanks for the great and incredibly fast answer!
Unfortunately, my requirements changed. Now the user can pretty much enter any format. Binary, Decimal, Hex. So I decided try - catch just provides the simplest and cleanest solution.
So just for good measure I am posting the code I am using now. I think it is pretty clear and even somewhat elegant, or so I think^^.
So thanks for encouraging me to use try - catch, I think it really improved the readibility of my code.
Thanks