Java 程序从给定位置提取“k”位
从数字的给定位置提取 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 + " bits from position " + pos + " in number " + number );
System.out.println("The extracted number is " + exNum );
}
}输出
Extract 3 bits from position 2 in number 20 The extracted number is 2
下面我们了解一下上述程序。
首先,定义数字、k 和位置的值。然后从数字的给定位置提取所需的 k 位。最后,显示提取后的数字。演示此过程的代码片段如下:-
int number = 20, k = 3, pos = 2;
int exNum = ((1 << k) - 1) & (number >> (pos - 1));
System.out.println("Extract " + k + " bits from position " + pos + " in number " + number );
System.out.println("The extracted number is " + exNum );
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP