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