Share via


C++ unsigned long and C# ulong inconsistency?

Question

Monday, September 19, 2011 11:49 PM

So here is the C++ code:

void TextString::WriteFileHeader(FILE *f)
{
    unsigned short len1 = 4;
    char *str1 = "FGDK";
    unsigned short len2 = 4;
    char *str2 = "Text";
    unsigned long type = 2;
    unsigned short len3 = 3;
    char *str3 = "txt";
    fwrite(&len1,sizeof(len1),1,f);
    fwrite(str1,len1,1,f);
    fwrite(&len2,sizeof(len2),1,f);
    fwrite(str2,len2,1,f);
    fwrite(&type,sizeof(type),1,f);
    fwrite(&len3,sizeof(len3),1,f);
    fwrite(str3,len3,1,f);
}

And here is my "equivalent" C# code:

 

        internal void WriteHeader(FILE f) {
            f.Write(BitConverter.GetBytes((ushort)4), 0, sizeof(ushort));
            f.Write(Encoding.UTF8.GetBytes("FGDK"), 0, (sizeof(byte) * 4));
            f.Write(BitConverter.GetBytes((ushort)4), 0, sizeof(ushort));
            f.Write(Encoding.UTF8.GetBytes("Text"), 0, (sizeof(byte) * 4));
            f.Write(BitConverter.GetBytes((ulong)2), 0, sizeof(ulong));
            f.Write(BitConverter.GetBytes((ushort)3), 0, sizeof(ushort));
            f.Write(Encoding.UTF8.GetBytes("txt"), 0, (sizeof(byte) * 3));
        }

But these both put out 2 different outputs, specifically on the unsigned long/ulong part. I believe the C++ code was compiled in Codelite (I'm about 90% sure, if not then VS).

 

What am I doing different? Is C++'s unsigned long different than C#'s ulong?

All replies (3)

Monday, September 19, 2011 11:56 PM âś…Answered | 1 vote

unsigned long, in C++, is 4 bytes - but in C#, ulong is 8 bytes.  In C++, unsigned int and unsigned long are the same - there's a separate type "unsigned long long" for an 8 byte, unsigned integer type.

 

You need to switch your C# to uint.

 

 

Reed Copsey, Jr. - http://reedcopsey.com
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".


Tuesday, September 20, 2011 12:07 AM

Then what is the point of having "unsigned long" then if "unsigned int" is the same? Ah, so confusing sometimes.

 

Thanks, I can now continue work! I just need to make sure I change everything from ulong to uint. :)


Tuesday, September 20, 2011 12:14 AM | 1 vote

Then what is the point of having "unsigned long" then if "unsigned int" is the same? Ah, so confusing sometimes.

 

Thanks, I can now continue work! I just need to make sure I change everything from ulong to uint. :)

That, btw, is why it's suggested (and I encourage) to use the new standards:

 

__int8, __int16, __int32, __int64 and their unsigned versions, ie: unsigned __int32

 

 

Reed Copsey, Jr. - http://reedcopsey.com
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".