Search code examples
c#cunsignedulong

add two unsigned value in C and C#


I have a calculation in c that I should write it in c#

this is my code in c:

const unsigned long *S //which is an array that already contains data ) 
unsigned long  y;
y = y + S[d]; //S[d] = 2582066069 and y = 3372499074 and the results is 1659597847

but in my C# code:

ulong[] S = (ulong[])hashtable[key];
ulong y = 2582066069;
y = y + S[d]; // s[d] = 3372499074 but the result is = 5954565143

I don't undrestand the difference in this add operation in c and c# would you pelase help me too undrestand where I am doing wrong?


Solution

  • In your C case, the unsigned long data size is 4 bytes while in C#, ulong data size is 8-bytes.

    unsigned long   4 bytes 0 to 4,294,967,295 //in C
    ulong           8 bytes 0 to 18,446,744,073,709,551,615 //in C#
    

    Thus in your C case, when you add the two values, you will get overflow.

    3372499074 + 2582066069 = 5954565143 (overflow) = (4294967296 + 1659597847) mod 4294967296 = 1659597847
    

    But in your C# case, the ulong data type is still able to hold the value without overflow.

    3372499074 + 2582066069 = 5954565143 (no overflow)
    

    Find out more of the data type value limit in C and in C#. Also check out this post for more understanding on C data type size (dbush's and delnan's answers are particularly helpful. Since there isn't some standardized size for long data type in C, in may sometimes be 4 bytes and sometimes 8 bytes - unlike C#'s counterpart, ulong is always 8 bytes)

    To have a 8 bytes unsigned integer data type in C, you could use uint64_t data type

    uint64_t u64;