c++到Java的代码移植使用位操作符和unsigned int
C++ to Java porting code with bitwise operators and unsigned int
我需要将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中被签名。
来自c++的long数据类型是一个64位有符号的二进制补码整数。它有最小值为-9,223,372,036,854,775,808,最大值为9223372036854775807(包容)。
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。所以,这没什么区别。更多信息请参考
相关文章:
- 对字符串进行位操作
- 对字符数组中的元素执行逐位操作
- 逐位操作的隐式类型转换
- 如何进行特定的位操作?
- C++避免位操作完全移位
- 使用双包装器类进行位操作(C++、clang)修复性能下降问题
- 使用位操作优化检查
- 子集相关位操作
- 使用 c++ 提升库的按位操作
- 位操作和异或
- 位操作将最左侧的设置位转换为右侧交替位?
- 为什么对小于 4 个字节的整数类型的位操作会发生意外行为?
- POD 类型的原子按位操作
- 如何使用位操作在单个整数中编码和解码两个数字
- __int128的位操作
- 使用位操作会影响内存消耗?
- 在具有位操作的函数中获得值
- C/C 位操作不会导致预期输出
- 在数组大小中使用位操作的原因
- 了解C++位操作中的二进制转换实现