JAvaシフト演算子">>""
5642 ワード
public class test19 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int a=2*4;
int b=2<<2; // 2*2^2
System.out.println(a+"//"+b);
int c=3<<2;
//0000 0000 0000 0000 0000 0000 0000 0011-->00 0000 0000 0000 0000 0000 0000 0011
//0000 0000 0000 0000 0000 0000 0000 1100-->1100-->12
System.out.println(c);
int d=11>>2; //0000 0000 0000 0000 0000 0000 0000 1000-->0000 0000 0000 0000 0000 0000 0000 10
//0000 0000 0000 0000 0000 0000 0000 0010--2
System.out.println(d);
int e=11>>>2; //8>>2==8/2*2
System.out.println(e);
}
}
java :<<( )、>>( ) >>>( )。
1、
<< 。
1) :
value << num
num value 。
: ,0
, 。 int 33 , 33%32=1 。
2)
, ( ), 。
int , 1 31 ;
long , 1 63 。
byte short , int 。
3)
, , 2 1 , n 2 n
4) :
:3 <<2(3 int )
1) 3 0000 0000 0000 0000 0000 0000 0000 0011,
2) ( ) , 2 ,
3) ( ) 。 0000 0000 0000 0000 0000 0000 0000 1100,
12。
,
(31 63 ), 。 :
Java
// Left shifting as a quick way to multiply by 2.
public class MultByTwo {
public static void main(String args[]) {
int i;
int num = 0xFFFFFFE;
for(i=0; i<4; i++) {
num = num << 1;
System.out.println(num);
}
}
}
// Left shifting as a quick way to multiply by 2.
public class MultByTwo {
public static void main(String args[]) {
int i;
int num = 0xFFFFFFE;
for(i=0; i<4; i++) {
num = num << 1;
System.out.println(num);
}
}
}
:
536870908
1073741816
2147483632
-32
:n , , -2^(n-1) ——2^(n-1) -1, 2^(n-1)。
2、
<< 。
1) :
value >> num
num value 。
: ,
2) :
, ( ), , , 1
byte short , int 。
, , 1, , 0, ( )(sign extension ),
。
3)
2, n 2 n 。
4)
11 >>2(11 int )
1)11 :0000 0000 0000 0000 0000 0000 0000 1011
2) , , 。
3) 0000 0000 0000 0000 0000 0000 0000 0010。
3。
35 >> 2(35 int )
35 :0000 0000 0000 0000 0000 0000 0010 0011
:0000 0000 0000 0000 0000 0000 0000 1000
: 8
5)
0x0f , , , 。
Java
public class HexByte {
public static public void main(String args[]) {
char hex[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f''
};
byte b = (byte) 0xf1;
System.out.println("b = 0x" + hex[(b >> 4) & 0x0f] + hex[b & 0x0f]);
}
}
public class HexByte {
public static public void main(String args[]) {
char hex[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f''
};
byte b = (byte) 0xf1;
System.out.println("b = 0x" + hex[(b >> 4) & 0x0f] + hex[b & 0x0f]);
}
}
(b >> 4) & 0x0f :
b :1111 0001
4 :0000 1111
:0000 1111
10 :15
b & 0x0f :
b :1111 0001
0x0f :0000 1111
:0000 0001
10 :1
, :
b = 0xf1
3、
>>>
:
value >>> num
num value 。
: ,0
>>> 32 64