簡體   English   中英

Java位操作長-刪除一些位

[英]Java Bit Operation on Long - Removing some bits

我電話很長。 現在,我要做的是以下幾點:

long l = "001000......10001100000" (bits representation)

我需要從左側除去它( 10)的 3 4 比特和剩余的62個比特轉換成長

long newl = "0000......10001100000" (bits representation)

有人可以幫我用Java有效地做到這一點嗎?

通常,您可以通過使用掩碼對它們進行“ OR 設置設置位; 您可以通過AND掩碼的補碼AND相加來清除位:

long mask = 3L << 60; // 001100...
long newl = l & ~mask;     // Clear the bits in the mask.

如果您要刪除這些位(並有效地將值縮短為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM