将Java代码转换为Python

时间:2015-04-13 12:29:53

标签: java python hex

我正在尝试将此Java代码翻译为Python:

double grades = -32.33f;
System.out.println("grades: "+grades);
double radians = Math.toRadians(grades);
System.out.println("rad: "+radians);
long radiansUp8 = 0xFFFF_FFFFL & (long)(radias * 100_000_000);
System.out.println("rad: "+radiansUp8);
String hex = Long.toHexString(radiansUp8);
System.out.println("signed to hex: "+hex);

我已经这样做了:

import math

grades = -32.33
radians = math.radians(grades)
print radians
radians = radians * 100000000
print radians
hexValue = hex(int(radians))
print hexValue

但我没有得到相同的结果。 Java代码工作正常,但在Python中没有。这一行特别是我不确定如何转换为Python,也许这就是问题所在:

long radiansUp8 = 0xFFFF_FFFFL & (long)(radianes * 100_000_000);

Java代码的(正确)输出是:

grades: -32.33000183105469
rad: -0.5642649791276998
rad: 4238540799
signed to hex: fca2ffff

Python代码的(错误的)输出是:

grades: -32.33
radians: -0.56426494717
radians: -56426494.717
signed to hex: -0x35cfffe

1 个答案:

答案 0 :(得分:1)

将该行转换为Python:

radians = 0xffffffff & long(radians * 100000000)

这给出了(大致!)你期望的答案:

>>> 0xffffffff & long(math.radians(-32.33) * 100000000)
4238540802L

行是将弧度数乘以100,000,000(给出-56426494.71697667),将结果转换为long整数(-56426494L)然后在0xffffffff>>> '{:04b}'.format(int('1010', 2) & (int('0111', 2))) '0010' 之间执行“按位和”(请参阅例如https://wiki.python.org/moin/BitwiseOperators)。您当前的代码只执行这三个步骤中的第一步。

关于按位和做的简单示例:

1

对于每个二进制数字,仅当两个输入数字均为1时,输出数字才为{{1}}。