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 ] );
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With