Fastest way to cast int to UInt32 bitwise?

好久不见. 提交于 2019-12-05 21:38:22

问题


i have some low level image/texture operations where 32-bit colors are stored as UInt32 or int and i need a really fast bitwise conversion between the two.

e.g.

 int color = -2451337;  

 //exception
 UInt32 cu = (UInt32)color;

any ideas?

thanks and regards


回答1:


int color = -2451337;
unchecked {
    uint color2 = (uint)color;
    // color2 = 4292515959
}



回答2:


BitConverter.ToUInt32(BitConverter.GetBytes(-2451337), 0)



回答3:


Those using a language like VB, which don't have a really convenient way of disabling overflow checks during the conversion, could use something like:

    Shared Function unsToSign64(ByVal val As UInt64) As Int64
        If (val And &H8000000000000000UL)  0 Then Return CLng(val Xor &H8000000000000000UL) Xor &H8000000000000000 Else Return CLng(val)
    End Function
    Shared Function signToUns64(ByVal val As Int64) As UInt64
        If val < 0 Then Return CULng(val Xor &H8000000000000000) Xor &H8000000000000000UL Else Return CULng(val)
    End Function

or

    Shared Function unsToSign(ByVal val As UInt64) As Int64
        Return CLng(val And &H7FFFFFFFFFFFFFFFUL) + (CLng(-((val And &H8000000000000000UL) >> 1)) << 1)
    End Function
    Shared Function signToUns(ByVal val As Int64) As UInt64
        Return CULng(val And &H7FFFFFFFFFFFFFFF) + (CULng(-((val And &H8000000000000000) >> 1)) << 1)
    End Function

Versions for 32 bits would be very similar. I'm not sure which approach would be faster. The shifts are a little silly, but they avoid the need for 'if' tests.



来源:https://stackoverflow.com/questions/3600871/fastest-way-to-cast-int-to-uint32-bitwise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!