C# 将 bool 重新解释为 byte/int(无分支) [英] C# reinterpret bool as byte/int (branch-free)

查看:56
本文介绍了C# 将 bool 重新解释为 byte/int(无分支)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 C# 中将 bool 转换为 byteint(或任何整数类型,真的)无需分支?

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(无分支)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆