7

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 ] );
            }
     }
}
8
  • 5
    Chars in C# are 2 bytes, so with an Int32 pointer you're going to get two chars per int. Commented Mar 24, 2015 at 16:42
  • If you know your characters are 8-bit friendly you could extract them and stuff four into each integer yourself, but you would need to make a copy of the data. Commented Mar 24, 2015 at 16:46
  • Please see "Should questions include “tags” in their titles?", where the consensus is "no, they should not"! Commented Mar 25, 2015 at 9:31
  • @AndreasNiedermair please mess somewhere else.. I want my title to be expressive of the problem so google can help Commented Mar 25, 2015 at 9:53
  • @sam Please follow my link: Stack Overflow is optimized so that tags are indexed by search engines along with the content of the question. ... and watch your tongue! Commented Mar 25, 2015 at 9:53

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.