/Users/lyon/j4p/src/utils/ByteUtil.java
|
1 package utils;
2
3 public class ByteUtil {
4 public static void printToDecimal(byte b) {
5 System.out.println(toInt(b));
6 }
7
8 public static int toInt(byte b) {
9 return
10 ((b >> 4) & 0xF) * 16 +
11 (b & 0xF);
12 }
13
14 public static String toString(byte b, int radix) {
15 return
16 Integer.toString(toInt(b), radix);
17 }
18
19 public static String toString(byte b) {
20 return toString(b, 10);
21 }
22
23 public static void printToHex(byte b) {
24 System.out.print("0x" + getHex(b));
25 }
26
27 public static void main(String[] args) {
28 testGetHex();
29 }
30
31 public static void testGetHex() {
32 byte b[] = {
33 0, 1, 16, 127
34 };
35 System.out.println(getHex(b));
36 }
37 /**
38 * Encode a byte array into a hexidecimal String
39 * @param b
40 * @return
41 */
42 public static String getHex(byte b[]) {
43 char hex[] = {
44 '0', '1', '2', '3', '4',
45 '5', '6', '7', '8', '9',
46 'A', 'B', 'C', 'D', 'E', 'F'};
47 StringBuffer sb = new StringBuffer();
48 for (int i = 0; i < b.length; i++)
49 sb.append(hex[(b[i] >> 4) & 0x0f] + "" + hex[b[i] & 0x0f]);
50 return sb.toString();
51 }
52
53 public static String getHex(byte b) {
54 char hex[] = {
55 '0', '1', '2', '3', '4',
56 '5', '6', '7', '8', '9',
57 'A', 'B', 'C', 'D', 'E', 'F'};
58 return hex[(b >> 4) & 0x0f] + "" + hex[b & 0x0f];
59 }
60
61 public static void printToOctal(byte b) {
62 char oct[] = {
63 '0', '1', '2', '3', '4',
64 '5', '6', '7'};
65 System.out.print("0" +
66 oct[(b >> 6) & 03] +
67 oct[(b >> 3) & 07] +
68 oct[b & 07] + " ");
69 }
70
71
72 }
73