如何根据 Javascript 的代码在 C# 中进行十进制按位运算
How to do decimal Bitwise Operation in C# from Javascript's Code
我正在将库从 javascript 翻译成 C#,在这种情况下感觉:
// Javascript
var number = 3144134277.518717 | 0;
console.log(number); // -> -1150833019
根据我在其他 post 上读到的内容,它可能被用来对值进行舍入,但在这种情况下,该值不是我期望的值(如果它被舍入)并且我无法在 C# 中重现相同的行为:
// C#
3144134277.5187168 | 0 // -> Operator '|' cannot be applied to operands
// of type 'double' and 'int'
// or
Convert.ToInt64(3144134277.5187168) | 0 // -> 3144134278
感谢您的帮助!
|
在javaScript中的工作方式详尽in the spec, but primarily what you're seeing is that |
implicitly converts its operands to 32-bit ints before doing the bitwise OR (which is a no-op because the second arg is 0
). So really what you're seeing is the result of the ToInt32
operation:
- 让数字是?
ToNumber(argument)
。 (你基本上可以忽略这一点。)
- 如果数字是
NaN
、+0
、-0
、+∞
或 -∞
、return +0
。
- 令int为与number同号且大小为
floor(abs(number))
. 的数学值
- 设int32bit为int模2^32.
- 如果int32bit ≥ 2^31, return int32bit - 2 ^32;否则 return int32bit.
所以在 C# 中,我认为大致是:
double value = 3144134277.5187168;
bool negative = value < 0;
long n = Convert.ToInt64(Math.Floor(Math.Abs(value)));
n = n % 4294967296;
n = n > 2147483648 ? n - 4294967296 : n;
int i = (int)n;
i = negative ? -i : i;
Console.WriteLine(i); // -1150833019
...为清楚起见,写得很冗长。请注意,符号并没有在与规范完全相同的位置添加回结果;当我这样做时,它无法正常工作,这可能与规范的 "modulo" 和 C# 的 %
运算符之间的不同定义有关。
并且仔细检查一下,-3144134277.5187168
的那些步骤给你 1150833019
,这也是应该的。
我正在将库从 javascript 翻译成 C#,在这种情况下感觉:
// Javascript
var number = 3144134277.518717 | 0;
console.log(number); // -> -1150833019
根据我在其他 post 上读到的内容,它可能被用来对值进行舍入,但在这种情况下,该值不是我期望的值(如果它被舍入)并且我无法在 C# 中重现相同的行为:
// C#
3144134277.5187168 | 0 // -> Operator '|' cannot be applied to operands
// of type 'double' and 'int'
// or
Convert.ToInt64(3144134277.5187168) | 0 // -> 3144134278
感谢您的帮助!
|
在javaScript中的工作方式详尽in the spec, but primarily what you're seeing is that |
implicitly converts its operands to 32-bit ints before doing the bitwise OR (which is a no-op because the second arg is 0
). So really what you're seeing is the result of the ToInt32
operation:
- 让数字是?
ToNumber(argument)
。 (你基本上可以忽略这一点。) - 如果数字是
NaN
、+0
、-0
、+∞
或-∞
、return+0
。 - 令int为与number同号且大小为
floor(abs(number))
. 的数学值
- 设int32bit为int模2^32.
- 如果int32bit ≥ 2^31, return int32bit - 2 ^32;否则 return int32bit.
所以在 C# 中,我认为大致是:
double value = 3144134277.5187168;
bool negative = value < 0;
long n = Convert.ToInt64(Math.Floor(Math.Abs(value)));
n = n % 4294967296;
n = n > 2147483648 ? n - 4294967296 : n;
int i = (int)n;
i = negative ? -i : i;
Console.WriteLine(i); // -1150833019
...为清楚起见,写得很冗长。请注意,符号并没有在与规范完全相同的位置添加回结果;当我这样做时,它无法正常工作,这可能与规范的 "modulo" 和 C# 的 %
运算符之间的不同定义有关。
并且仔细检查一下,-3144134277.5187168
的那些步骤给你 1150833019
,这也是应该的。