将按位Java操作转换为Python

时间:2014-05-28 19:39:05

标签: java python bit-manipulation

我的问题很简单。我有一个用Java编写的客户端程序,它有一个生成ID的方法。我正在编写Python脚本来解析和更正此客户端程序的输出。创建ID的客户端中的方法使用按位操作来创建ID。不幸的是,ID生成器虽然是UUID,但它不是唯一的。

我尝试转换的代码是开源的,并且在EMF EcoreUtil.java文件1中。如果您有时间或寻找有趣的编码,欢迎您翻译此代码。但我想知道如何像在C / C ++和Java中那样在python中执行这样的按位操作。

2 个答案:

答案 0 :(得分:3)

python中的按位操作与它们在C / Java中的相同(虽然python缺少Java的>>>操作,因为它不需要;符号扩展总是完成,但即使0xFFFF_FFFF_FFFF_FFFF也可以表示为一个正整数)。

作为一个额外的好处,Python整数可以用于任何大小的正面,与Java不同,Java中存在签名问题。

查看链接文件,似乎该值确实应该是UUID,只是它是base64编码的:

  

生成通用唯一标识符,即UUID。它编码   基数为64的128位UUID,而不是填充编码   两个“=”字符,它在编码前加上一个“_”   字符,以确保结果是有效的ID,即NCName

在Python中有UUID类和base64编码模块;因此整个标识符处理可以用Python编写

import uuid
import base64

gen_id = uuid.uuid1()  # generate type 1 UUID
id_bytes = gen_id.bytes  # take its bytes
encoded = base64.b64encode(id_bytes, b'-_')
encoded = encoded.replace(b'=', b'')  # remove the padding bytes
result = '_' + encoded.decode('ascii')  # result is a string with '_' prepended.

答案 1 :(得分:1)

Python wiki有一个good page on this。我不太了解Java,但初看起来我认为许多运营商都是一样的:

此外,您可能需要查看uuid module

运营商:

x << y Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.
x >> y Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.
x & y  Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.
x | y  Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1.
~ x    Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1.
x ^ y  Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.