简体   繁体   English

如何将ulong转换为正整数?

[英]How can I convert a ulong to an positive int?

I have a piece of code that is 我有一段代码是

// Bernstein hash
// http://www.eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx           
ulong result = (ulong)s[0];
for ( int i = 1; i < s.Length; ++i ) 
{ 
    result = 33 * result + (ulong)s[i]; 
}
return (int)result % Buckets.Count; 

and the problem is that it's sometimes returning negative values. 问题是它有时返回负值。 I know the reason is because (int)result can be negative. 我知道原因是因为(int)result可能为负。 But I want to coerce it to be non-negative since it's used as an index. 但是我想强迫它为非负数,因为它被用作索引。 Now I realize I could do 现在我意识到我可以做

int k = (int)result % Buckets.Count; 
k = k < 0 ? k*-1 : k;
return k; 

but is there a better way? 但是有更好的方法吗?

On a deeper level, why is int used for the index of containers in C#? 更深入地讲,为什么在C#中将int用作容器的索引? I come from a C++ background and we have size_t which is an unsigned integral type. 我来自C ++背景,我们有size_t ,这是一个无符号整数类型。 That makes more sense to me. 这对我来说更有意义。

Use 采用

return (int)(result % (ulong)Buckets.Count);

As you sum up values you reach a positive integer number that cannot be expressed as a positive number in a signed 32 bit integer. 在对值求和时,您将获得一个正整数,该正整数不能以带符号的32位整数表示为正数。 The cast to int will return a negative number. 强制转换为int将返回负数。 The modulo operation will then also return a negative number. 然后,取模操作还将返回负数。 If you do the modulo operation first, you will get a low positive number and the cast to int will do no harm. 如果先进行模运算,则将得到一个低的正数,并且强制转换为int不会造成任何损害。

While you can find a way to cast this to an int properly, I'm wondering why you don't just calculate it as an int from the beginning. 尽管您可以找到一种将其正确转换为int ,但我想知道为什么您不从一开始就将其作为int计算。

int result = (int)s[0]; // or, if s[0] is already an int, omit the cast
for ( int i = 1; i < s.Length; ++i ) 
{ 
    result = 33 * result + (int)s[i]; 
}
return Math.Abs(result) % Buckets.Count;

As to why C# uses a signed int for indexes, it has to do with cross-language compatibility . 关于C# 为什么将带符号的int用于索引,它与跨语言兼容性有关

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM