在 C# 中将单个十六进制字符转换为其字节值
这会将 1 个十六进制字符转换为其整数值,但需要构造一个(子)字符串。
Convert.ToInt32(serializedString.Substring(0,1), 16);
.NET 是否有一种内置方法可以将单个十六进制字符转换为其字节(或 int,无关紧要)值,并且不涉及创建新字符串?
This will convert 1 hex character to its integer value, but needs to construct a (sub) string.
Convert.ToInt32(serializedString.Substring(0,1), 16);
Does .NET have a built-in way to convert a single hex character to its byte (or int, doesn't matter) value that doesn't involve creating a new string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我添加另一个答案只是因为没有人提到这个。 您可以使用内置的 < code>Uri.FromHex 转换单个字符的方法:
I am adding another answer just because no one mentioned this one. You can use the built-in
Uri.FromHex
method for converting a single character:更便宜的可能是:
这只会将感兴趣的字符添加到 char[] 中,而不是整个字符串。
Cheaper might be:
This will only add the interesting char to the char[] and not the entire string.
或者甚至更快(减法与数组搜索),但不检查错误输入:
Or even faster (subtraction vs. array search), but no checking for bad input:
您就可以简单地使用吗
如果我错了,请纠正我,但是只要 stringValue 代表十六进制数字, ? 这不是基本参数的重点吗?
字符串是不可变的,我认为没有办法在不创建新字符串的情况下获取索引 0 处 char 的子字符串字节值
Correct me if im wrong but can you simply use
as long as the stringValue represents a hex number? Isnt that the point of the base paramter?
Strings are immutable, I dont think there is a way to get the substring byte value of the char at index 0 without creating a new string
如果您知道十六进制值只是一个字节,那么只需转换为 Int32 然后进行强制转换
If you know the hex value is only a byte then just convert to an Int32 and then cast
当然,您无需创建另一个字符串即可获取十六进制值。 我不确定它会给你带来什么,从性能角度来看,但既然你问了,这就是你所要求的。
Sure you can get the hex value without ever needing to create another string. I'm not sure what it'll really gain you, performance wise, but since you asked, here's what you've requested.