public static String toHexString(ByteBuffer buffer,int offset,int size,boolean formatted){
  int bufLen=size * 2;
  if (formatted) {
    bufLen+=size + (7 * ((size + NUM_BYTES_PER_LINE - 1) / NUM_BYTES_PER_LINE));
  }
  StringBuilder rtn=new StringBuilder(bufLen);
  int position=buffer.position();
  buffer.position(offset);
  size=Math.min(size,buffer.remaining());
  for (int i=0; i < size; i++) {
    byte b=buffer.get();
    byte h=(byte)(b & 0xF0);
    h=(byte)(h >>> 4);
    h=(byte)(h & 0x0F);
    rtn.append(HEX_CHARS[h]);
    h=(byte)(b & 0x0F);
    rtn.append(HEX_CHARS[h]);
    int next=(i + 1);
    if (formatted && (next < size)) {
      if ((next % NUM_BYTES_PER_LINE) == 0) {
        rtn.append("\n");
      }
 else {
        rtn.append(" ");
        if ((next % NUM_BYTES_PER_BLOCK) == 0) {
          rtn.append(" ");
        }
      }
    }
  }
  buffer.position(position);
  return rtn.toString();
}

public static String toHexString ( ByteBuffer buffer , int offset , int size , boolean formatted ) { int bufLen = size * 2 ; if ( formatted ) { bufLen += size + ( 7 * ( ( size + NUM_BYTES_PER_LINE - 1 ) / NUM_BYTES_PER_LINE ) ) ; } StringBuilder rtn = new StringBuilder ( bufLen ) ; int position = buffer . position ( ) ; buffer . position ( offset ) ; size = Math . min ( size , buffer . remaining ( ) ) ; for ( int i = 0 ; i < size ; i ++ ) { byte b = buffer . get ( ) ; byte h = ( byte ) ( b & 0xF0 ) ; h = ( byte ) ( h > > > 4 ) ; h = ( byte ) ( h & 0x0F ) ; rtn . append ( HEX_CHARS [ h ] ) ; h = ( byte ) ( b & 0x0F ) ; rtn . append ( HEX_CHARS [ h ] ) ; int next = ( i + 1 ) ; if ( formatted && ( next < size ) ) { if ( ( next % NUM_BYTES_PER_LINE ) == 0 ) { rtn . append ( "\n" ) ; } else { rtn . append ( " " ) ; if ( ( next % NUM_BYTES_PER_BLOCK ) == 0 ) { rtn . append ( " " ) ; } } } } buffer . position ( position ) ; return rtn . toString ( ) ; }
convert a byte buffer to a hexadecimal string for display
