从数字中给定位置提取k位涉及将数字转换为其二进制表示形式。一个例子如下:
Number = 20 Binary representation = 10100 k = 3 Position = 2 The bits extracted are 010 which represent 2.
演示此过程的程序如下。
public class Example { public static void main (String[] args) { int number = 20, k = 3, pos = 2; int exNum = ((1 << k) - 1) & (number >> (pos - 1)); System.out.println("Extract " + k + " 从位置开始的位 " + pos + " in number " + number ); System.out.println("提取的号码是 " + exNum ); } }
输出结果
Extract 3 从位置开始的位 2 in number 20 提取的号码是 2
现在让我们了解上面的程序。
首先,定义数字,k和位置的值。然后从数字中的给定位置提取所需的k位。最后,显示提取的号码。证明这一点的代码片段如下-
int number = 20, k = 3, pos = 2; int exNum = ((1 << k) - 1) & (number >> (pos - 1)); System.out.println("Extract " + k + " 从位置开始的位 " + pos + " in number " + number ); System.out.println("提取的号码是 " + exNum );