Pergunta

Eu tenho algumas operações de imagem/textura de baixo nível, onde as cores de 32 bits são armazenadas como UINT32 ou INT e preciso de uma conversão muito rápida bit-bit entre os dois.

por exemplo

 int color = -2451337;  

 //exception
 UInt32 cu = (UInt32)color;

alguma ideia?

Obrigado e cumprimentos

Foi útil?

Solução

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

Outras dicas

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

Aqueles que usam um idioma como o VB, que não têm uma maneira realmente conveniente de desativar verificações de transbordamento durante a conversão, poderiam usar algo como:

    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

ou

    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

Versões para 32 bits seriam muito semelhantes. Não tenho certeza de qual abordagem seria mais rápida. As mudanças são um pouco bobas, mas evitam a necessidade de testes 'se'.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top