View Javadoc

1   /*
2    *   @(#) $Id: ByteBufferHexDumper.java 210062 2005-07-11 03:52:38Z trustin $
3    *
4    *   Copyright 2004 The Apache Software Foundation
5    *
6    *   Licensed under the Apache License, Version 2.0 (the "License");
7    *   you may not use this file except in compliance with the License.
8    *   You may obtain a copy of the License at
9    *
10   *       http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *   Unless required by applicable law or agreed to in writing, software
13   *   distributed under the License is distributed on an "AS IS" BASIS,
14   *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   *   See the License for the specific language governing permissions and
16   *   limitations under the License.
17   *
18   */
19  package org.apache.mina.common;
20  
21  import org.apache.mina.common.ByteBuffer;
22  
23  /***
24   * Provides utility methods for ByteBuffers.
25   * 
26   * @author Trustin Lee (trustin@apache.org)
27   * @version $Rev: 210062 $, $Date: 2005-07-11 12:52:38 +0900 $
28   */
29  class ByteBufferHexDumper
30  {
31      private static final byte[] highDigits;
32  
33      private static final byte[] lowDigits;
34  
35      // initialize lookup tables
36      static
37      {
38          final byte[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
39                                 '9', 'A', 'B', 'C', 'D', 'E', 'F' };
40  
41          int i;
42          byte[] high = new byte[ 256 ];
43          byte[] low = new byte[ 256 ];
44  
45          for( i = 0; i < 256; i++ )
46          {
47              high[ i ] = digits[ i >>> 4 ];
48              low[ i ] = digits[ i & 0x0F ];
49          }
50  
51          highDigits = high;
52          lowDigits = low;
53      }
54  
55      static String getHexdump( ByteBuffer in )
56      {
57          int size = in.remaining();
58  
59          if( size == 0 )
60          {
61              return "empty";
62          }
63  
64          StringBuffer out = new StringBuffer( ( in.remaining() * 3 ) - 1 );
65  
66          int mark = in.position();
67  
68          // fill the first
69          int byteValue = in.get() & 0xFF;
70          out.append( ( char ) highDigits[ byteValue ] );
71          out.append( ( char ) lowDigits[ byteValue ] );
72          size--;
73  
74          // and the others, too
75          for( ; size > 0; size-- )
76          {
77              out.append( ' ' );
78              byteValue = in.get() & 0xFF;
79              out.append( ( char ) highDigits[ byteValue ] );
80              out.append( ( char ) lowDigits[ byteValue ] );
81          }
82  
83          in.position( mark );
84  
85          return out.toString();
86      }
87  }