如何快速将ReadonlySpan<byte>转换为int类型?
将ReadOnlySpan转换为int类型的方法
因为你的ReadOnlySpan<byte>中的元素是ASCII编码的数字字符(52对应'4',48对应'0',55对应'7'),直接用.NET内置的解析方法就能完成转换,无需手动处理单个字节:
两种常用实现方式
1. 直接解析(适用于确定内容合法的场景)
ReadOnlySpan<byte> byteSpan = new byte[] { 52, 48, 48, 55, 48 }; int result = int.Parse(byteSpan, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
2. 安全解析(适用于不确定内容是否合法的场景,避免抛出异常)
ReadOnlySpan<byte> byteSpan = new byte[] { 52, 48, 48, 55, 48 }; if (int.TryParse(byteSpan, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int tryResult)) { // 转换成功,使用tryResult } else { // 转换失败,执行错误处理逻辑 }
原理说明
int.Parse和int.TryParse的ReadOnlySpan<byte>重载会自动将ASCII字节序列映射为对应的数字字符串,再解析成int类型,完全匹配你的需求。
内容的提问来源于stack exchange,提问作者Fernando
相关产品推荐
相关产品推荐

