題目:取一個整數 a 從右端(最低位)開始的第 4~7 位(共 4 位)。即保留二進位的 bit 3~6(0-indexed)。
int a = 0b101100110101; // 範例
int mask = 0b1111 << 3; // 0b1111000 = 0x78
int result = (a & mask) >> 3;
步驟:
0b1111 (低 4 位全 1) 左移 3 位 → 0b1111000。a & mask 保留目標 4 位,其餘歸零。
public class BitExtract {
public static void main(String[] args) {
long b = 18745678;
// 取十進位的第 4~7 位(非二進位位元!)
int a = (int) Math.floor(b % Math.pow(10, 7) / Math.pow(10, 3));
System.out.println(a); // 輸出 4567
}
}
注意:原始碼實際是在處理十進位數字的「第 4~7 位數字」,而非二進位位元。兩者含義完全不同,實務上請確認需求。
public static int getBits(int value, int fromBit, int toBit) { // 0-indexed, inclusive
int len = toBit - fromBit + 1;
int mask = (1 << len) - 1;
return (value >> fromBit) & mask;
}
// 使用範例:取 bit 3~6
int result = getBits(a, 3, 6);
支援任意位元範圍擷取,建議收藏備用。