重新解释将数组从string转换为int

Mau*_*tro 7 c# arrays casting

我想在int数组中重新解释一个字符串,其中每个int根据处理器架构负责4或8个字符.

有没有办法以相对便宜的方式实现这一目标?我试过这个,但似乎没有在一个int中重新解释4个字符

string text = "abcdabcdefghefgh";

unsafe
{
    fixed( char* charPointer = text )
    {
        Int32* intPointer = (Int32*)charPointer;

        for( int index = 0; index < text.Length / 4; index++ )
        {
            Console.WriteLine( intPointer[ index ] );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

解决方案:(根据您的需要更改Int64或Int32)

string text = "abcdabcdefghefgh";

unsafe
{
    fixed( char* charPointer = text )
    {
            Int64* intPointer = (Int64*)charPointer;
            int conversionFactor = sizeof( Int64 ) / sizeof( char );

            int index = 0;
            for(index = 0; index < text.Length / conversionFactor; index++)
            {
                Console.WriteLine( intPointer[ index ] );
            }

            if( text.Length % conversionFactor != 0 )
            {
                intPointer[ index ] <<= sizeof( Int64 );
                intPointer[ index ] >>= sizeof( Int64 );

                Console.WriteLine( intPointer[ index ] );
            }
     }
}
Run Code Online (Sandbox Code Playgroud)

usr*_*usr 4

你几乎做对了。sizeof(char) == 2 && sizeof(int) == 4。循环转换因子必须是 2,而不是 4。它是sizeof(int) / sizeof(char)。如果您喜欢这种风格,您可以使用这种精确的表达方式。sizeof是一个鲜为人知的 C# 功能。

请注意,如果长度不均匀,现在您会丢失最后一个字符。

关于性能:您所做的事情是尽可能便宜的。