int i = 13; // i is 00000000 00000000 00000000 0000 1101
i = i << 2; // i is 00000000 00000000 00000000 0011 0100
After this left shift, i becomes 52 which is same as multiplying i by 4 Zero fill shift right is represented by the symbol >>>. This operator fills the leftmost bits by zeros. So the result of applying the operator >>> is always positive. (In two's complement representation the leftmost bit is the sign bit. If sign bit is zero, the number is positive, negative otherwise.) The example below illustrates applying the operator >>> on a number.
int b = 13; // 00000000 00000000 00000000 0000 1101
b = b >>> 2; // b is now 00000000 00000000 00000000 0000 0011
So the result of doing a zero fill right shift by 2 on 13 is 3. The next example explains the effect of applying the operator >>> on a negative number.
int b = -11; //11111111 11111111 11111111 1111 0101
b = b >>> 2; // b now becomes 00111111 11111111 11111111 1111 1101
So the result of applying zero fill right shift operator with operand two on -11 is 1073741821. Signed right shift operator (>>) fills the left most bit by the sign bit. The result of applying the signed shift bit has the same sign as the left operand. For positive numbers the signed right shift operator and the zero fill right shift operator both give the same results. For negative numbers, their results are different. The example below illustrates the signed right shift.
int b = -11; // 11111111 11111111 11111111 1111 0101
b = b >> 2; // 11111111 11111111 11111111 1111 1101 (2's complement of -3) // Here the sign bit 1 gets filled in the two most significant bits.
The new value of b becomes -3.1. How to generate a random number between 1 to x, x being a whole number greater than 1
Ans: double result = x * Math.random();
No comments:
Post a Comment