Converting Small endian to Big Endian using C#(long value)

Could someone tell me how to write an equivalent code in C# for the following C++ code which would give me a big endian from a small endian Thanking you in Advance..

Function call - ProcessEndian((char*) &longValue,
sizeof(long));

void CUtility::ProcessEndian(char * pHostData, int nHostDataLength)
{
char buffer[10];
int i = 0;
char* pChar = NULL;

for (i=0; i<nHostDataLength; i++)
{
pChar = pHostData+i;
buffer[ i ] = *(pChar);
}

for (i=0; i<nHostDataLength; i++)
{
*pChar = buffer[ i ];
pChar--;
}
}



Answer this question

Converting Small endian to Big Endian using C#(long value)

  • Ender Uygun

    Thanks a Lot James..this code was used in C++ to convert a small endian to a long endian when setting search params in a struct for CICS Client dll call.. i had to do the same using C#.Net..using Marshalling...

    so i had to reverse this value(long) bytes before setting the search param field(long).

    Thanks once again..


  • Nate Dunlap

    First of all, overwriting a varaible like that is just plain wrong, and has been outlawed in .Net (and Java, and it's really frowned upon in C++)

    But, if you only want to handle integer types, you can use IPAddress.HostToNetworkOrder

    The equivalent to you call would be

    longValue = IPAddress.HostToNetworkOrder(longValue);

    It's overloaded to handle shorts, ints, and longs.

    If that's not good enough (and it really should be), look into the BitConverter class. With that it would be something like:

    byte[] temp = BitConverter.GetBytes(longValue);
    Array.Reverse(temp);
    longValue = BitConverter.ToInt32(temp);

    There appears to be no way of getting around knowing the destination type in the final step.



  • Converting Small endian to Big Endian using C#(long value)