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

标签 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 ] );
        }
    }
}

解决方案:(根据您的需要更改 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# 特性。

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

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

关于c# - 重新解释将数组从字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29238240/

相关文章:

C# - 已建立的连接被主机错误中的软件中止

c# - 使用 Entity Framework 时出现 InvalidCastException

python - 取数组中每2个数据点的平均值,创建一个新数组

javascript - 使用 JS 循环创建的元素与另一个元素重叠

java - Kotlin 中的动态转换

c# - 我可以创建自定义隐式类型转换吗?

c# - ObservableCollection CollectionChanged 事件似乎没有触发——为什么?

c++ - 对通过引用传递给它的第一个元素的数组进行操作

C# 从字符串转换为 int 或 int32。可能的?

c# - 如何*轻松*公开底层对象的方法?