简体   繁体   English

Java使用移位将long的位分为两部分

[英]Java split the bits of a long in two parts using bit shifting

I need to split the bits of a number say 9( 1001 ) in two equal sized parts 10 and 01 in this case. 在这种情况下,我需要将数字的位数9( 1001 )分成两个相等大小的部分1001

My first idea was to just shift it but for the right number I dont get the expected result ,I suspect this is due to the sign(no unsigned in java :( ). 我的第一个想法是只是移动它,但对于正确的数字我没有得到预期的结果,我怀疑这是由于符号(在java :()中没有未签名的原因)。

My current code is the following: 我当前的代码如下:

long num=9;
System.out.println(Long.toBinaryString(num));
long num1=num>>2;
System.out.println(Long.toBinaryString(num1));
long num2=num<<2;
System.out.println(Long.toBinaryString(num2));

Output: 输出:

1001
10
100100

Any workaround? 任何解决方法?

To get the lower part, you need to use bitwise AND... so if you shift right by 2 bits to get the higher part, you need to AND with binary number 11 (two bits as 1) to get the lower part. 要获得较低的部分,您需要使用按位AND ...,因此,如果向右移位2位以获取较高的部分,则需要将二进制数为11(两位为1)进行AND以获得较低的部分。 Here's code which should do it for any shift: 下面的代码应该对任何转变进行处理:

long num = 9;
int shift = 2

System.out.println(Long.toBinaryString(num));
long num1 = num >> shift;
System.out.println(Long.toBinaryString(num1));
long num2 = num & ( (1<<shift) - 1);
System.out.println(Long.toBinaryString(num2));

Explanation of calculating num2 , for shift 2, 0b means binary literal, in pseudocode: 计算num2说明,对于shift 2,0b表示二进制文字,以伪代码表示:

( (1<<shift) - 1) == ( (1<<2) - 1)  == ( 0b100 - 1) == 0b11 == two bits set

From that it should be clear how it will work for any shift value. 从中应该清楚它对于任何shift值如何工作。

You could shift num1 back 2 and the subtract it from num . 您可以将num1移回2并从num减去它。 This will give you num2 . 这将给你num2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM