[英]Java Bit Operation on Long - Removing some bits
I have a long number. 我电话很长。 Now, what I want to do is the following: 现在,我要做的是以下几点:
long l = "001000......10001100000" (bits representation)
I need to remove the 3 rd and 4 th bits of it ( ie 10) from the left and convert the remaining 62 bits to long 我需要从左侧除去它( 即 10)的第 3 次和第 4 次比特和剩余的62个比特转换成长
long newl = "0000......10001100000" (bits representation)
Can anybody help me do this efficiently in Java ? 有人可以帮我用Java有效地做到这一点吗?
You typically set bits by OR
ing them with a mask; 通常,您可以通过使用掩码对它们进行“ OR
设置来设置位; you clear bits by AND
ing them with the complement of a mask: 您可以通过AND
掩码的补码AND
相加来清除位:
long mask = 3L << 60; // 001100...
long newl = l & ~mask; // Clear the bits in the mask.
If you're looking to remove the bits (and effectively shorten the value to 62 bits), then you can try this: 如果您要删除这些位(并有效地将值缩短为62位),则可以尝试以下操作:
long topBits = ((3L << 62) & l) >> 2; // Top 2 bits, shifted right
long bottomBits = (~(15L << 60) & l); // Bottom 60 bits
long newl = topBits | bottomBits;
如果您将位列表作为字符串,则只需从该字符串中删除第3位和第4位,然后使用Long.parseLong(string, 2)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.