Training Java – part 7 – how work shift bits?

In this post you find out how work shift bits in number.

Begin with this example:

public class Test {
public static void main(String[] ar )
{	
 int b = 0b1010;
 
System.out.print("b = ");  System.out.print(b);   
System.out.print(",b binary = ");  
System.out.println(Integer.toBinaryString(b));
    System.out.println(); 

System.out.print("b1 ;    
System.out.print("b>>1 = ");  System.out.println(b>>1);     
System.out.println("binary = "+Integer.toBinaryString(c));
    System.out.println();   
    
int d = b>>>1;  
System.out.print("b>>>1 = ");  System.out.println(b>>>1);     
System.out.println("binary = "+Integer.toBinaryString(d));
    System.out.println();      
}
}

Result:

And second example shows you bitshift in negative number. The code is the same except line with asign value to b variable.

public class Test {
public static void main(String[] ar )
{	
int b = -11;
...
}
}

Result:
The diffrence between >> and >>> operators is that first count  value from number only for accurate bits, for -10 number it is only 4 bits. The >> operator is  signed right shift operator. Second operator is unsigned right shift operator and  count value from all bits in number, so this value is diffrent. For negative number first digits are 1 so they are counting. For positive numbers this first places are zero, so they are  count  for >>> operator but are zero so value for  these bits are zero.