/Users/lyon/j4p/src/utils/Encoder.java
|
1 package utils;
2
3
4 public class Encoder {
5 private static final char digits[] = {
6 '0', '1', '2', '3', '4', '5',
7 '6', '7', '8', '9', 'a', 'b',
8 'c', 'd', 'e', 'f', 'g', 'h',
9 'i', 'j', 'k', 'l', 'm', 'n',
10 'o', 'p', 'q', 'r', 's', 't',
11 'u', 'v', 'w', 'x', 'y', 'z',
12 '!', '@', '#', '$', '%', '^',
13 '&', '*', '(', ')', '`', '~',
14 ';', ':', '<', '>', ',', '.',
15 '/', '?', '[', ']', '{', '}',
16 '\\', '|', '=', '_'
17 };
18
19 public static void main(String args[]) {
20 int i = 646;
21 //convert to base 64 numeral
22 // can you convert the following to a for loop?
23 int d1 = i / 64;
24 int d1a = i % 64;
25 int d2 = d1 / 64;
26 int d2a = d1 % 64;
27 int d3 = d2 / 64;
28 int d3a = d2 % 64;
29 int d4 = d3 / 64;
30 int d4a = d3 % 64;
31 int d5 = d4 / 64;
32 int d5a = d4 % 64;
33 int d6 = d5 / 64;
34 int d6a = d5 % 64;
35 int d7 = d6 / 64;
36 int d7a = d6 % 64;
37 int d8 = d7 / 64;
38 int d8a = d7 % 64;
39
40 //digits ending in 'a' represent the remainders of the preceding digits
41 System.out.println(i);
42 System.out.println("converted to base 64 numeral = ");
43 System.out.print(digits[d8a]);
44 System.out.print(digits[d7a]);
45 System.out.print(digits[d6a]);
46 System.out.print(digits[d5a]);
47 System.out.print(digits[d4a]);
48 System.out.print(digits[d3a]);
49 System.out.print(digits[d2a]);
50 System.out.println(digits[d1a]);
51 }
52
53 public static String toBaseR(int i, int shift) {
54 char[] buf = new char[64];
55 int charPos = 64;
56 int radix = 1 << shift;
57 int mask = radix - 1;
58 do {
59 buf[--charPos] = digits[i & mask];
60 i >>>= shift;
61 } while (i != 0);
62 return new String(buf);
63 }
64
65 public static void main2(String args[]) {
66 int num = 0xffff;
67 System.out.println(Encoder.toBaseR(num, 4));
68 }
69 }
70