C# 中的 strtoul 等效项
我正在尝试将配置文件中的一堆无符号整数读入类中。这些数字可以以 10 为基数(例如:1234)或以 16 为基数(例如:0xAB31)指定。因此,寻找 C# 2.0 中的 strtoul
等效项。
更具体地说,我对一个 C# 函数感兴趣,当指示基数或基数的参数作为零传入时,该函数会模仿此函数的行为。 (在 C++ 下,strtoul 将尝试根据字符串中的前几个字符“猜测”基数或基数,然后继续适当地转换数字)
目前我正在手动检查前两个字符串的字符(使用 string.Substring()
方法),然后调用 Convert.ToUInt32(hex, 10)
或 Convert.ToUInt32(hex, 16)根据需要。
我确信必须有更好的方法来处理这个问题,因此这篇文章。更优雅的想法/解决方案或解决方法将会有很大的帮助。
I'm trying to read-in a bunch of unsigned integers from a configuration file into a class. These numbers may be specified in either base-10 (eg: 1234) or in base-16 (eg: 0xAB31). Therefore looking for the strtoul
equivalent in C# 2.0.
More specifically, I'm interested in a C# function which mimics the behaviour of the this function when the argument indicating the base or radix is passed in as zero. (Under C++, strtoul
will attempt to 'guess' the base or radix based on the first couple of characters in the string and then proceed to convert the number suitably)
Currently I'm manually checking the first two characters (using string.Substring()
method) of the string and then calling Convert.ToUInt32(hex, 10)
or Convert.ToUInt32(hex, 16)
as needed.
I'm sure that there has to be a better way to deal with this problem and hence this post. More elegant ideas/solutions or work-arounds would be great help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,你不需要使用 Substring ,除非它是十六进制的,但听起来你基本上是以正确的方式做的:
显然这将为
Substring
调用创建一个额外的对象,并且你可以编写您自己的十六进制解析代码来解决这个问题 - 但除非您确实遇到了这种方法的性能问题,否则我会保持简单。Well, you don't need to use Substring unless it's in hex, but it sounds like you're basically doing it the right way:
Obviously this will create an extra object for the
Substring
call, and you could write your own hex parsing code to cope with this - but unless you've actually run into performance problems with this approach, I'd keep it simple.