package canghailan.util; |
02 |
03 | /** |
04 | * @author canghailan 2012-03-02 21:31 |
05 | */ |
06 | public class Bytes { |
07 | private static final char [] DIGITS = { |
08 | '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f' |
09 | }; |
10 |
11 | public static String toBinaryString( byte b) { |
12 | int u = toUnsigned(b); |
13 | return new String( new char []{ |
14 | DIGITS[(u >>> 7 ) & 0x1 ], |
15 | DIGITS[(u >>> 6 ) & 0x1 ], |
16 | DIGITS[(u >>> 5 ) & 0x1 ], |
17 | DIGITS[(u >>> 4 ) & 0x1 ], |
18 | DIGITS[(u >>> 3 ) & 0x1 ], |
19 | DIGITS[(u >>> 2 ) & 0x1 ], |
20 | DIGITS[(u >>> 1 ) & 0x1 ], |
21 | DIGITS[u & 0x1 ] |
22 | }); |
23 | } |
24 |
25 | public static String toBinaryString( byte ... bytes) { |
26 | char [] buffer = new char [bytes.length * 8 ]; |
27 | for ( int i = 0 , j = 0 ; i < bytes.length; ++i) { |
28 | int u = toUnsigned(bytes[i]); |
29 | buffer[j++] = DIGITS[(u >>> 7 ) & 0x1 ]; |
30 | buffer[j++] = DIGITS[(u >>> 6 ) & 0x1 ]; |
31 | buffer[j++] = DIGITS[(u >>> 5 ) & 0x1 ]; |
32 | buffer[j++] = DIGITS[(u >>> 4 ) & 0x1 ]; |
33 | buffer[j++] = DIGITS[(u >>> 3 ) & 0x1 ]; |
34 | buffer[j++] = DIGITS[(u >>> 2 ) & 0x1 ]; |
35 | buffer[j++] = DIGITS[(u >>> 1 ) & 0x1 ]; |
36 | buffer[j++] = DIGITS[u & 0x1 ]; |
37 | } |
38 | return new String(buffer); |
39 | } |
40 |
41 | public static String toHexString( byte b) { |
42 | int u = toUnsigned(b); |
43 | return new String( new char []{ |
44 | DIGITS[u >>> 4 ], |
45 | DIGITS[u & 0xf ] |
46 | }); |
47 | } |
48 |
49 | public static String toHexString( byte ... bytes) { |
50 | char [] buffer = new char [bytes.length * 2 ]; |
51 | for ( int i = 0 , j = 0 ; i < bytes.length; ++i) { |
52 | int u = toUnsigned(bytes[i]); |
53 | buffer[j++] = DIGITS[u >>> 4 ]; |
54 | buffer[j++] = DIGITS[u & 0xf ]; |
55 | } |
56 | return new String(buffer); |
57 | } |
58 |
59 | private static int toUnsigned( byte b) { |
60 | return b < 0 ? b + 256 : b; |
61 | } |
62 | } |
1 | public static void main(String[] args) throws Exception { |
2 | byte [] bytes = ByteBuffer.allocate( 8 ).putLong(Long.MAX_VALUE).array(); |
3 | System.out.println(Bytes.toHexString(bytes)); |
4 | } |