0

我在 c 中有一个计算,我应该用 c# 编写它

这是我在 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

但在我的 C# 代码中:

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

我不明白 c 和 c# 中的这个添加操作的区别你能不能帮我理解我做错了什么?

4

1 回答 1

5

在您的C情况下,unsigned long数据大小为4 byteswhile in C#ulong数据大小为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#

因此,在您的C情况下,当您添加两个值时,您将溢出。

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

但是在您的C#情况下,ulong数据类型仍然能够保持该值而不会溢出。

3372499074 + 2582066069 = 5954565143 (no overflow)

了解更多CC#中的数据类型值限制。另请查看这篇文章,以进一步了解C数据类型大小(dbushdelnanlong的答案特别有帮助。由于 in 中的数据类型没有一些标准化的大小C, in 有时可能是4 bytes有时8 bytes- 与C#'s 的对应项不同,ulong总是8 bytes

8 bytes unsigned integer在 C 中使用数据类型,您可以使用uint64_t数据类型

uint64_t u64;
于 2016-03-24T11:28:58.527 回答