C# reinterpret bool as byte/int (branch-free)(C# 将 bool 重新解释为 byte/int(无分支))
问题描述
是否可以在 C# 中将 bool 转换为 byte 或 int(或任何整数类型,真的)无需分支?
Is it possible in C# to turn a bool into a byte or int (or any integral type, really) without branching?
换句话说,这不够:
var myInt = myBool ? 1 : 0;
我们可能会说我们想将 bool 重新解释为底层 byte,最好用尽可能少的指令.目的是避免分支预测失败,如 这里.
We might say we want to reinterpret a bool as the underlying byte, preferably in as few instructions as possible. The purpose is to avoid branch prediction fails as seen here.
推荐答案
unsafe
{
byte myByte = *(byte*)&myBool;
}
另一个选项是 系统.Runtime.CompilerServices.Unsafe,在非核心平台上需要 NuGet 包:
Another option is System.Runtime.CompilerServices.Unsafe, which requires a NuGet package on non-Core platforms:
byte myByte = Unsafe.As<bool, byte>(ref myBool);
CLI 规范仅将 false 定义为 0 并将 true 定义为除 0 之外的任何内容,所以从技术上讲可能无法在所有平台上按预期工作.但是,据我所知,C# 编译器还假设 bool 只有两个值,所以在实践中我希望它能够在大多数学术案例之外工作.
The CLI specification only defines false as 0 and true as anything except 0 , so technically speaking this might not work as expected on all platforms. However, as far as I know the C# compiler also makes the assumption that there are only two values for bool, so in practice I would expect it to work outside of mostly academic cases.
这篇关于C# 将 bool 重新解释为 byte/int(无分支)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 将 bool 重新解释为 byte/int(无分支)
- C# 中多线程网络服务器的模式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
