重新解释将数组从字符串转换为整数

reinterpret cast an array from string to int

我想重新解释 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 ] );
        }
    }
}

解决方案:(根据您的需要更改 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 ] );
            }
     }
}

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

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

关于性能:您完成它的方式是尽可能便宜的。