c++到Java的代码移植使用位操作符和unsigned int

C++ to Java porting code with bitwise operators and unsigned int

本文关键字:位操作 操作符 int unsigned Java 代码 c++      更新时间:2023-10-16

我需要将c++代码翻译成Java。我有两件事很担心。

1)将'unsigned int'从c++翻译为'long'。我选择使用long来增加存储容量。

2)使用位操作符,特别是|和<<考虑到我已经把unsigned int转换成long了对这些经营者有什么不良影响吗?例如在c++中:

unsigned int a;
unsigned int b;
unsigned int c;
a | (b<<c)

在Java中是否可以这样做:

long a, b, c;
a | (b<<c)

请让我知道你认为我可能会遇到的任何问题做这些事

谢谢

应该可以。记住,Java long是64位的。唯一真正的区别是Java整数是有符号的。

操作符的行为应该与unsigned相同:+, -, ==, &, |, ^, <<

这些将改变行为:*, /, %, <

使用>>>代替>>来对/2**k进行无符号解释(推入的位是0,而不是MSB副本)。

long在Java中被签名。

long数据类型是一个64位有符号的二进制补码整数。它有最小值为-9,223,372,036,854,775,808,最大值为9223372036854775807(包容)。

来自c++的

unsigned int是一个字长(32位在32位机器上)。取值范围为0 ~ 4294967295。

我相信你所做的是安全的,应该在Java中工作得很好。您所展示的按位操作应该可以正常工作。

       Bitwise operations
  It's important to remember that the unsigned keyword affects 
  the interpretation, not the representation of a number. In other 
  words, in cases where we aren't interpreting a value arithmetically— so-called
  bitwise operations such as AND, OR, XOR— it makes essentially no 
  difference whether a value is marked as "signed" or "unsigned"

。Unsigned int相当于java中的long。所以,这没什么区别。更多信息请参考