按位运行int到UInt32的最快方法?

tha*_*alm 8 c# casting copy uint32

我有一些低级别的图像/纹理操作,其中32位颜色存储为UInt32或int,我需要在两者之间进行非常快速的按位转换.

例如

 int color = -2451337;  

 //exception
 UInt32 cu = (UInt32)color;
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

感谢致敬

sis*_*sve 21

int color = -2451337;
unchecked {
    uint color2 = (uint)color;
    // color2 = 4292515959
}
Run Code Online (Sandbox Code Playgroud)


Jad*_*ias 8

BitConverter.ToUInt32(BitConverter.GetBytes(-2451337), 0)
Run Code Online (Sandbox Code Playgroud)

  • +1来抵消downvote.甚至在我编辑之前,这个答案就没有任何重要的错误.事实上,如果使用VB,这将是首选方法,因为不允许从Int32到UInt32的直接转换和粒度未经检查的上下文. (2认同)