Java语言的移位运算符: <<, >>, >>>共3种.
publicclass Test
{
publicstaticvoidmain(String[] args)
{
/*
* 移位运算符只对byte,short,int,long和char类型有效
*/
//有(无)符号数, 左移(<<),最高位符号位都将被右边的位覆盖
bytenum = (byte)0x8F;
num<<= 1;
System.out.println("10001111<< 1 = " + Integer.toBinaryString(num));
num = (byte)0x7F;
num<<= 1;
System.out.println("01111111<< 1 = " + Integer.toBinaryString(num));
//有(无)符号数, 右移(>>),最高位符号位都将保留
num = (byte)0x8F;
num>>= 1;
System.out.println("10001111>> 1 = " + Integer.toBinaryString(num));
num = (byte)0x7F;
num>>= 1;
System.out.println("01111111>> 1 = " + Integer.toBinaryString(num));
//有(无)符号数(只对32位和64位数有效),无符号右移(>>>),最高位符号位都将变成0
intn =0x8FFFFFFF;
n>>>= 1;
System.out.println("0x8FFFFFFF>>> 1 = " + Integer.toHexString(n));
n =0x7FFFFFFF;
n>>>= 1;
System.out.println("0x7FFFFFFF>>> 1 = " + Integer.toHexString(n));
}
}
运算结果,如下:
10001111 << 1 = 00011110
01111111 << 1 = 11111110
10001111 >> 1 = 11000111
01111111 >> 1 = 00111111
0x8FFFFFFF >>> 1 = 0x47FFFFFF
0x7FFFFFFF >>> 1 = 0x 3FFFFFFF
C++语言的移位运算符: <<, >>共2种.
int _tmain(int argc, _TCHAR* argv[])
{
/*
* 移位运算符最好只对整数类型运算,这样才有意义
*/
//有(无)符号数, 左移(<<),最高位符号位都将被右边的位覆盖
char num =(char)0x8F;
num<<= 1;
printf("0x8F<< 1 = 0x%02X\n", num);
num =(char)0x7F;
num<<= 1;
printf("0x7F<< 1 = 0x%02X\n", num);
//有(无)符号数, 右移(>>),最高位符号位都将保留
num =(char)0x8F;
num>>= 1;
printf("0x8F>> 1 = 0x%02X\n", num);
num =(char)0x7F;
num>>= 1;
printf("0x7F>> 1 = 0x%02X\n", num);
return 0;
}
运算结果,如下:
0x8F << 1 =0x1E
0x7F << 1 = 0xFE
0x8F >> 1 =0xC7
0x7F >> 1 = 0x3F
C#语言的移位运算符: <<, >>共2种.
public static void Main(string[] args)
{
/*
* 移位运算符最好只对整数类型运算,这样才有意义
*/
//有(无)符号数, 左移(<<),最高位符号位都将被右边的位覆盖
sbyte sNum= unchecked((sbyte)0x8F);
sNum<<= 1;
Console.WriteLine("0x8F<< 1 = 0x{0,-2:X2}", sNum);
byte usNum= unchecked((byte)0x7F);
usNum<<= 1;
Console.WriteLine("0x7F<< 1 = 0x{0,-2:X2}", usNum);
//有(无)符号数, 右移(>>),最高位符号位都将保留
sNum =unchecked((sbyte)0x8F);
sNum>>= 1;
Console.WriteLine("0x8F>> 1 = 0x{0,-2:X2}", sNum);
usNum =unchecked((byte)0x7F);
usNum>>= 1;
Console.WriteLine("0x7F>> 1 = 0x{0,-2:X2}", usNum);
Console.ReadKey();
}
运算结果,如下(与C++的结果相同):
0x8F << 1 =0x1E
0x7F << 1 = 0xFE
0x8F >> 1 =0xC7
0x7F >> 1 = 0x3F
原文:http://blog.csdn.net/newboy686/article/details/44706305