Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reinterpret cast an array from string to int

Tags:

arrays

c#

casting

I'd like to reinterpret a string in a array of int where every int take charge of 4 or 8 chars based on processor architecture.

Is there a way to achieve this in a relatively inexpensive way? I tried out this but doesn't seem to reinterpret 4 chars in one int

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

SOLUTION: (change Int64 or Int32 based on your needs)

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 ] );
            }
     }
}
like image 524
Mauro Sampietro Avatar asked Mar 24 '15 16:03

Mauro Sampietro


1 Answers

You almost got it right. sizeof(char) == 2 && sizeof(int) == 4. The loop conversion factor must be 2, not 4. It's sizeof(int) / sizeof(char). If you like this style you can use this exact expression. sizeof is a little known C# feature.

Note, that right now you lose the last character if the length is not even.

About performance: The way you have done it is as inexpensive as it gets.

like image 176
usr Avatar answered Oct 01 '22 18:10

usr