|
| 1 | +package benblack86.binary; |
| 2 | + |
| 3 | +public class BasicBinary { |
| 4 | + public static void main(String args[]) { |
| 5 | + |
| 6 | + System.out.printf("Capacity of primitives:\n"); |
| 7 | + System.out.printf(" byte [ 8 bits] min:%s max:%s\n", Byte.MIN_VALUE, Byte.MAX_VALUE); |
| 8 | + System.out.printf(" short [16 bits] min:%s max:%s\n", Short.MIN_VALUE, Short.MAX_VALUE); |
| 9 | + System.out.printf(" int [32 bits] min:%s max:%s\n", Integer.MIN_VALUE, Integer.MAX_VALUE); |
| 10 | + System.out.printf(" long [64 bits] min:%s max:%s\n", Long.MIN_VALUE, Long.MAX_VALUE); |
| 11 | + |
| 12 | + // 0x => hexadecimal (0xF => 15, 0x10 => 16) |
| 13 | + // 0b => binary (0b11 => 3) |
| 14 | + |
| 15 | + // i >> x: shift bits in i right by x positions (2 >> 1 => 1) |
| 16 | + // i << x: shift bits in i left by x positions (1 << 1 => 2) |
| 17 | + |
| 18 | + System.out.printf("\nPrint binary using method 1:\n"); |
| 19 | + for(int i = 125; i < 130; i++) { |
| 20 | + printBinary(i); |
| 21 | + } |
| 22 | + printBinary(-100); |
| 23 | + |
| 24 | + System.out.printf("\nPrint binary using method 2:\n"); |
| 25 | + for(int i = 125; i < 130; i++) { |
| 26 | + printBinary2(i); |
| 27 | + } |
| 28 | + printBinary2(-100); |
| 29 | + |
| 30 | + |
| 31 | + System.out.printf("\nBinary operations:\n"); |
| 32 | + printBinary(128); // 00000000000000000000000010000000 (128) |
| 33 | + printBinary(~128); // 11111111111111111111111101111111 (-129) |
| 34 | + printBinary(-128); // 11111111111111111111111110000000 (-128) |
| 35 | + printBinary(~-128); // 00000000000000000000000001111111 (127) |
| 36 | + printBinary(128>>>1); // 00000000000000000000000001000000 (64) |
| 37 | + printBinary(128>>>2); // 00000000000000000000000000100000 (32) |
| 38 | + printBinary(128>>1); // 00000000000000000000000001000000 (64) |
| 39 | + printBinary(128>>2); // 00000000000000000000000000100000 (32) |
| 40 | + printBinary(-127>>>1);// 01111111111111111111111111000000 (2147483584) |
| 41 | + printBinary(-127>>>2);// 00111111111111111111111111100000 (1073741792) |
| 42 | + printBinary(-127>>1); // 11111111111111111111111111000000 (-64) |
| 43 | + printBinary(-127>>2); // 11111111111111111111111111100000 (-32) |
| 44 | + } |
| 45 | + |
| 46 | + public static void printBinary(int i) { |
| 47 | + System.out.printf("%12s: ", i); |
| 48 | + for(int k = 31; k > -1; k--) { |
| 49 | + // need abs to work with negative numbers |
| 50 | + System.out.printf("%s", Math.abs(i >> k) % 2); |
| 51 | + } |
| 52 | + System.out.printf("\n"); |
| 53 | + } |
| 54 | + |
| 55 | + public static void printBinary2(int i) { |
| 56 | + System.out.printf("%12s: ", i); |
| 57 | + for(int k = 31; k > -1; k--) { |
| 58 | + // shift bit to the most significant position and apply mask |
| 59 | + System.out.printf("%s", i >> k & 0b1); |
| 60 | + } |
| 61 | + System.out.printf("\n"); |
| 62 | + } |
| 63 | +} |
0 commit comments