Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说java移位操作示例「终于解决」,希望能够帮助你!!!。
public class Shift4JTest {
/** *移位操作符有>>(右移)、<<(左移)、>>>(右移) * >>是带符号右移,负数高位补1,正数高位补0 * <<左移不管负数还是正数,在低位永远补0 * >>>是不带符号右移,不论负数还是正数,高位补0 */
public static void main(String[] args) {
int a = 10;
int b = a << 1; //相当于 乘以2的1次幂
int c = a << 2; //相当于 乘以2的2次幂
int d = a << 3; //相当于 乘以2的3次幂
BitUtil.getFull32BinaryString(a);
System.out.println(b);
BitUtil.getFull32BinaryString(b);
System.out.println(c);
BitUtil.getFull32BinaryString(c);
System.out.println(d);
BitUtil.getFull32BinaryString(d);
}
public class BitUtil {
public static String getFull32BinaryString(Integer a){
String s = Integer.toBinaryString(a);
int count = 32 - s.length();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++) {
sb.append("0");
if (i != 0 && i % 8 == 0) sb.append(" ");
}
sb.append(s);
System.out.println(sb.toString());
return sb.toString();
}
}
}
int a = 80;
int b = a >> 1; //相当于 除以2的1次幂
int c = a >> 2; //相当于 除以2的2次幂
int d = a >> 3; //相当于 除以2的3次幂
System.out.println(a);
BitUtil.getFull32BinaryString(a);
System.out.println(b);
BitUtil.getFull32BinaryString(b);
System.out.println(c);
BitUtil.getFull32BinaryString(c);
System.out.println(d);
BitUtil.getFull32BinaryString(d);
int a = -80;
int b = a >> 1; //相当于 除以2的1次幂
int c = a >> 2; //相当于 除以2的2次幂
int d = a >> 3; //相当于 除以2的3次幂
System.out.println(a);
BitUtil.getFull32BinaryString(a);
System.out.println(b);
BitUtil.getFull32BinaryString(b);
System.out.println(c);
BitUtil.getFull32BinaryString(c);
System.out.println(d);
BitUtil.getFull32BinaryString(d);
//正数>>>和>> 是一样的
int a = 80;
int b = a >>> 1; //相当于 除以2的1次幂
int c = a >>> 2; //相当于 除以2的2次幂
int d = a >>> 3; //相当于 除以2的3次幂
System.out.println(a);
BitUtil.getFull32BinaryString(a);
System.out.println(b);
BitUtil.getFull32BinaryString(b);
System.out.println(c);
BitUtil.getFull32BinaryString(c);
System.out.println(d);
BitUtil.getFull32BinaryString(d);
//在负数的情况下>>>和>> 是不一样的
//>>>不论正负数 高位永远补0
int a = -80;
int b = a >>> 1;
int c = a >>> 2;
int d = a >>> 3;
System.out.println(a);
BitUtil.getFull32BinaryString(a);
System.out.println(b);
BitUtil.getFull32BinaryString(b);
System.out.println(c);
BitUtil.getFull32BinaryString(c);
System.out.println(d);
BitUtil.getFull32BinaryString(d);