Java Integer rotateLeft()方法
位移动是一种位操作,它是通过将二进制值的所有位向左或向右移动一定数量的位来进行的。Java有一个逻辑左移操作符(<<)。当值0001(即1)被左移时,它变成了0010(即2),再向左移就变成了0100或4。
java.lang.Integer.rotateLeft()方法用于将一个Integer值的位向左移动,以其二进制2的补码形式表示,移动指定的位数。(比特被移到左边或高阶)。
语法。
public static int rotateLeft(int value, int shifts)
参数。该方法需要两个参数。
a : 这是一个整数类型的参数,指的是要对其进行操作的值。shifts : 这也是整数类型的,指的是旋转的距离。返回值。该方法返回通过将指定的int值的二进制补码向左旋转指定的移位数得到的值。
例子
Input: 12Output: 24**Explanation:**Consider an integer a = 12 Binary Representation = 00001100After 1 left shift it will become=00011000So that is= 24
下面的程序说明了java.lang.Integer.rotateLeft()方法。
程序1: 对于一个正数。
// Java program to illustrate the// Java.lang.Integer.rotateLeft() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { int a = 2; int shifts = 0; while (shifts < 6) // It will return the value obtained by rotating left { a = Integer.rotateLeft(a, 2); System.out.println(a); shifts++; } }}输出。
83212851220488192
程序2: 对于一个负数。
// Java program to illustrate the// Java.lang.Integer.rotateLeft() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { int a = -16; int shifts = 0; while (shifts < 2) // It will return the value obtained by rotating left { a = Integer.rotateLeft(a, shifts); System.out.println(a); shifts++; } }}输出。
-16-31
程序3: 对于一个十进制值和字符串。
注意: 当十进制值和字符串作为参数传递时,它将返回一个错误信息
// Java program to illustrate the// Java.lang.Integer.rotateLeft() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { int a = 15.71; int shifts = 0; while (shifts < 2) { a = Integer.rotateLeft(a, shifts); System.out.println(a); shifts++; } int b = "61"; int shifts2 = 0; while (shifts2 < 2) { b = Integer.rotateLeft(b, shifts2); System.out.println(b); shifts2++; } }}输出。
prog.java:9: error: incompatible types: possible lossy conversion from double to int int a = 15.71; ^prog.java:18: error: incompatible types: String cannot be converted to int int b = "61"; ^2 errors
