代码之家  ›  专栏  ›  技术社区  ›  Mauro Sampietro

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

  •  7
  • Mauro Sampietro  · 技术社区  · 11 年前

    我想重新解释一个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 ] );
                }
         }
    }
    
    1 回复  |  直到 11 年前
        1
  •  4
  •   usr    11 年前

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

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

    关于性能:你做这件事的方式尽可能便宜。