java - Logical and Arithmetic shift's output -


here's tiny java program

public class otherclass { public static void main(string[]args){         byte a=-5;          byte d= (byte) (a>>>1);         system.out.println(d);         byte e= (byte) (a>>>2);         system.out.println(e);         byte f= (byte) (a>>1);         system.out.println(f);         byte g= (byte) (a>>2);         system.out.println(g); } } 

output:

-3 -2 -3 -2 

the second 2 outputs (those -3 , -2 of logical shifts) understand.

negative 5 11111011

arithmetic shift shifts right , added bit on left msb. 1 shift makes 11111101 negative 3. negative 2 fine.

the logical shift supposed add zeros left. 11111011 should become 01111101 125. how output negative 3?

the missing piece of information java promotes values int when bit-shifting them, called binary numeric promotion. byte values promoted int before shifted, shift occurs, cast byte.

-5 byte  : 11111011 -5 int   : 11111111 11111111 11111111 11111011 bit shifted : 01111111 11111111 11111111 11111101 

the 0 shifted in, cast byte discards last 8 bits anyway.

cast byte: 11111101 (-3) 

if >>> operation behave if there no binary numeric promotion, must mask out final 8 bits promoted int.

byte d= (byte) ((a & 0xff)>>>1); system.out.println(d); byte e= (byte) ((a & 0xff)>>>2); system.out.println(e); 

output:

125 62 

what's happening here:

-5 byte  : 11111011 -5 int   : 11111111 11111111 11111111 11111011 bit masked  : 00000000 00000000 00000000 11111011 bit shifted : 00000000 00000000 00000000 01111101 

the 0 shifted in before, cast byte discards last 8 bits anyway.

cast byte: 01111101 (125) 

note occur >>> , >>, bit-and 0xff on >>> operations.


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -