PiotrG
PiotrG

Reputation: 871

C++ to C# Code Conversion Types

I am trying to convert the following to C# but I am not getting expected results.

C++ Code:

DWORD CCSKW::GetCS(CString strFile)
{
    try
    {
        CFile file(strFile, CFile::modeRead);
        WORD wTemp = 0;
        WORD wCS = 0;

        const UINT uiMaxCharRead = 2000;
        TCHAR c[uiMaxCharRead];
        UINT uiCharRead;

        #ifdef _UNICODE
            while(uiCharRead = file.Read(c, uiMaxCharRead))
            {
                for(UINT i=0; i < uiCharRead; i++)
                    wCS ^= c[0];
            }
        #else
            while(uiCharRead = file.Read(c, uiMaxCharRead))
            {
                for(UINT i=0; i < uiCharRead-1; i++)
                {
                    wTemp = c[i];
                    i++;
                    wTemp <<= 8;
                    wTemp   += c[i];
                    wCS ^= wTemp;
                }
            }
        #endif
        file.Close();
        return (DWORD)wCS;
    }
    catch(CFileException *e)
    {
        e->ReportError();           
        e->Delete();                
    }
    return 0;
}

Briefly what this code does is reads a value from a binary file and returns it. This value is then used for a checksum calculation method.

My C# Code:

public UInt32 GetCS()
{
    try
    {
        ushort wTemp = 0;
        ushort wCS = 0;
        byte[] buffer = new byte[2000];

        int count;
        using (FileStream fs = new FileStream(csFile, FileMode.Open))
        {
            while ((count = fs.Read(buffer, 0, buffer.Length)) > 0)
            {
                for (int i = 0; i < count - 1; i++)
                {
                    wTemp = buffer[i];
                    i++;
                    wTemp <<= 8;
                    wTemp += buffer[i];
                    wCS ^= wTemp;
                }
            }
        }
        return Convert.ToUInt32(wCS);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
    return 0;
}

I know it might be difficult to help without knowing all the code, but I would just like to know if I am on the right track or if I have made some obvious errors.

Thank you!

Upvotes: 1

Views: 410

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109822

The issue here is that the C++ code is using TCHAR, which is a signed 8-bit type, but the C# code is using byte, which is an unsigned 8-bit type.

That means this line of code:

wTemp += buffer[i];

will always increase the value of wTemp in the C# code because buffer[i] is unsigned, but in the C++ code it will decrease the value of wTemp for values of buffer[i] >= 0x80.

You can fix this by changing the offending line to:

unchecked { wTemp = (ushort)(wTemp + (sbyte)buffer[i]); }

After doing that, your sample file will produce a result of 0x3336, as expected.

Upvotes: 1

Related Questions