微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 重新解释将数组从string转换为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#功能.

注意,如果长度不均匀,那么现在你丢失了最后一个字符.

关于性能:你做到这一点的方式和它一样便宜.

原文地址:https://www.jb51.cc/csharp/99340.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐