import static java.lang.System.out;
class u1a {
public static void main (String[] args) {
byte b;
int i;
out.printf(“Type extending and truncating — see slides\n”);
b = -6;
i = b;
// I am extending or promoting b by storing 1 byte into a 4 byte integer
out.printf (“b: 0x%x %d\t i: 0x%x %d\n”, b, b, i, i);
//out.printf (“b: %s 0x%x %d\t\t i: %s 0x%x %d\n”, Integer.toBinaryString(b & 0xff), b, b, Integer.toBinaryString(i), i, i);
b = -6;
i = b & 0xff;
out.printf (“EXTE b: %s 0x%x %d\t\t i: %32s 0x%8x %d\n”, Integer.toBinaryString(b & 0xff), b, b, Integer.toBinaryString(i), i, i);
// I am truncating i by storing 4 bytes into 1 byte
i = -6;
b = (byte) i;
out.printf (“TRUN b: %s 0x%x %d\t\t i: %s 0x%8x %d\n”, Integer.toBinaryString(b & 0xff), b, b, Integer.toBinaryString(i), i, i);
i = 256;
b = (byte) i;
out.printf (“TRUN b: %8s 0x%2x %d\t\t i: %32s 0x%8x %d\n”, Integer.toBinaryString(b & 0xff), b, b, Integer.toBinaryString(i), i, i);
i = 128;
b = (byte) i;
out.printf (“TRUN b: %8s 0x%2x %d\t\t i: %32s 0x%8x %d\n”, Integer.toBinaryString(b & 0xff), b, b, Integer.toBinaryString(i), i, i);
// Shifting bits
out.printf(“\n\nShifting Bits\n”);
int j;
i = -1;
j = i<<1;
out.printf ("LEFT i: %32s 0x%8x %d\t\t j: %32s 0x%8x %d\n", Integer.toBinaryString(i), i, i, Integer.toBinaryString(j), j, j);
j = i>>1;
out.printf (“RIGH i: %32s 0x%8x %d\t\t j: %32s 0x%8x %d\n”, Integer.toBinaryString(i), i, i, Integer.toBinaryString(j), j, j);
j = i>>>1;
out.printf (“RIGH i: %32s 0x%8x %d\t\t j: %32s 0x%8x %d\n”, Integer.toBinaryString(i), i, i, Integer.toBinaryString(j), j, j);
j = i<<33;
out.printf ("LEFT i: %32s 0x%8x %d\t\t j: %32s 0x%8x %d\n", Integer.toBinaryString(i), i, i, Integer.toBinaryString(j), j, j);
byte c;
b = -1;
c = (byte) (b<<1);
out.printf ("LEFT b: %8s 0x%2x %d\t\t\t\t\t\t c: %8s 0x%2x %d\n", Integer.toBinaryString(b & 0xff), b, b, Integer.toBinaryString(c & 0xff), c, c);
c = (byte) (b<<8);
out.printf ("LEFT b: %8s 0x%2x %d\t\t\t\t\t\t c: %8s 0x%2x %d\n", Integer.toBinaryString(b & 0xff), b, b, Integer.toBinaryString(c & 0xff), c, c);
c = (byte) (b>>1);
out.printf (“RIGH b: %8s 0x%2x %d\t\t\t\t\t\t c: %8s 0x%2x %d\n”, Integer.toBinaryString(b & 0xff), b, b, Integer.toBinaryString(c & 0xff), c, c);
b = 1;
c = (byte) (b>>1);
out.printf (“RIGH b: %8s 0x%2x %d\t\t\t\t\t\t c: %8s 0x%2x %d\n”, Integer.toBinaryString(b & 0xff), b, b, Integer.toBinaryString(c & 0xff), c, c);
b = -1;
c = (byte) (b>>>1);
out.printf (“RIGH b: %8s 0x%2x %d\t\t\t\t\t\t c: %8s 0x%2x %d\n”, Integer.toBinaryString(b & 0xff), b, b, Integer.toBinaryString(c & 0xff), c, c);
// Bitwise operations
out.printf(“\n\nBitwise Operations\n”);
i = Integer.parseInt(“0f0f0f0f”,16); //random bit pattern
out.printf (“BOP i: %32s 0x%8x %d\n”, Integer.toBinaryString(i), i, i);
j = i ^ 0xffffffff;
out.printf (“XOR j: %32s 0x%8x %d\n”, Integer.toBinaryString(j), j, j);
j = j | (1<<2); // turn bit on
out.printf ("BON j: %32s 0x%8x %d\n", Integer.toBinaryString(j), j, j);
}
}