开发者

Converting code from C to Java: shifts

I have some C code, where an unsigned integer is shifted by a (signed) variable. For example,

1u << i;开发者_StackOverflow中文版

When converting to Java, can I just replace it with a signed int?

I think it would be safe for left shifts, but I am not sure about right shifts.


In Java, there are two types of right shifts. >>> will attach 0's to fill the empty spaces for both positive and negative numbers (logical shift right) while >> will attach 1's if negative and 0's if positive (sign extension).

In C and C++, >> will insert zeros if the number is positive. However, with negative numbers, this case is implementation dependent. Either zeros or ones might be attached.

JavaScript behaves the same way as Java for >> and >>>.

In C#, when using >> for negative numbers, all the exposed bits except for the first are set to 0. The first stays at 1.

Note that for all the above languages, >> with positive numbers attaches zeros. Only the case with negative numbers varies. Also, << attaches zeros to the exposed bits for all languages.


It's fine for left shifts, for right-shifts use the >>> operator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜