0

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?

lol
  • 93
  • 3
  • 11

1 Answers1

5

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;
Community
  • 1
  • 1
Ian
  • 30,182
  • 19
  • 69
  • 107
  • Correct, this is an C error, and C# is managed. You can not reproduce overflow like in C withing C#. You could use modulo (%) operator to recreate an equal behaviour for that exact scenario. – Mafii Mar 24 '16 at 11:34
  • @Mafii That's not correct. C# has the ability to check for overflow and throw an exception but that can be turned on or off at the compiler level or in the code with `checked` and `unchecked`. – juharr Mar 24 '16 at 11:37
  • oh, I wasn't aware about that. Is the code still called managed then? – Mafii Mar 24 '16 at 11:38
  • 2
    @Mafii arithmetic overflow has nothing to do with it being a managed language. Managed just means it takes care of allocation and de-allocation of memory for you. – juharr Mar 24 '16 at 11:40
  • 2
    "unsigned long data size is 4 bytes".. well not always, but in this case could be. – Giorgi Moniava Mar 24 '16 at 11:47
  • 1
    `uint64_t` will be better than `unsigned long long` – phuclv Mar 24 '16 at 11:56