Hex Dump : Hex « Date Type « Android






Hex Dump

 
//package org.terukusu.util;

import java.io.UnsupportedEncodingException;


import android.util.Log;

/**
 * ?????????????
 * 
 * @author Teruhiko Kusunoki&lt;<a href="teru.kusu@gmail.com">teru.kusu@gmail.com</a>&gt;
 *
 */
public class Utils {
  
  /**
   * ????????????????
   */
  protected Utils() {
  }

  /**
   * ?????16?????????????
   * ????????????????????????????????????
   * 
   * @param data ????
   * @return 16???????????????
   */
  public static String hexDump(byte[] data) {
    return hexDump(data, null);
  }

  /**
   * ?????16?????????????
   * 
   * @param data ????
   * @param encoding ?????????????
   * @return 16???????????????
   */
  public static String hexDump(byte[] data, String encoding) {
    StringBuilder sb = new StringBuilder();

    if (encoding == null) {
      encoding = System.getProperty("file.encoding");
    }

    final int bytesPerLine = 16;

    int i = 0;
    for (i = 0; i < data.length; i++) {
      if (i % bytesPerLine == 0) {
        if (i > 0) {
          sb.append("  ");
          try {
            sb.append(new String(data, i - bytesPerLine, bytesPerLine, encoding));
          } catch (UnsupportedEncodingException e) {
            throw new Exception(e.getMessage(), e);
          }
          sb.append("\n");
        }
        sb.append(String.format("%08x:", i));
      } else if (i % 4 == 0) {
        sb.append(' ');
      }

      sb.append(String.format(" %02x", data[i]));
    }
    
//    Log.v(Constants.LOG_TAG, "data size: " + data.length + ", dumped size: " + i);

    if (i % bytesPerLine != 0) {
      if (i / bytesPerLine > 0) {
        for (int j = i; j % bytesPerLine != 0; j++) {
          if (j % 4 == 0) {
            sb.append(" ");
          }
          sb.append("   ");
        }
      }
      sb.append("  ");
      try {
        sb.append(new String(data, i - i % bytesPerLine, i % bytesPerLine, encoding));
      } catch (UnsupportedEncodingException e) {
        throw new Exception(e.getMessage(), e);
      }
      sb.append("\n");
    }
    
    return sb.toString();
  }
}

   
  








Related examples in the same category

1.converts given byte array to a hex string
2.converts given hex string to a byte array (ex: "0D0A" => {0x0D, 0x0A,})
3.Color name and its hex value
4.hex To Decimal
5.Get Hex string out of byte array
6.get Brightness, get Hex Name
7.String to Hex
8.Convenience method to convert a byte to a hex string.
9.Convenience method to convert a byte array to a hex string.
10.Convert a byte[] array to readable string format. This makes the "hex" readable!
11.Decode Unicode Hex
12.byte Array To Hex String