Here you can find the source of byteToHexStr(byte src, int len, int code)
public static String byteToHexStr(byte src, int len, int code)
//package com.java2s; //License from project: Apache License public class Main { public static String byteToHexStr(byte src, int len, int code) { return longToHexStr(src, len, code); }/*from w w w . ja v a 2s .co m*/ public static String longToHexStr(long src, int len, int code) { String HexStr = null; if (code == 0) { HexStr = asciiToHexStr(String.format("%d", src)); int llen = len - HexStr.length(); HexStr = fillString(HexStr, 0, llen, (byte) 30); } else if (code == 1) { byte[] tmp = new byte[16]; StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < 16; i++) { tmp[i] = (byte) (src >> 4 * (16 - i - 1) & 0xf); sBuilder.append(String.format("%X", tmp[i])); } HexStr = sBuilder.toString(); int llen = len - HexStr.length(); HexStr = fillString(HexStr, 0, llen, (byte) 0); } else { throw new RuntimeException("code type is not support"); } return HexStr.substring(0, len); } public static String asciiToHexStr(String src) { StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < src.length(); i++) sBuilder.append(String.format("%02X", Integer.valueOf(src.charAt(i)))); return sBuilder.toString(); } private static String fillString(String src, int direct, int len, byte fill) { if (len <= 0) return src; for (int i = 0; i < len; i += String.valueOf(fill).length()) { //left if (direct == 0) { src = String.valueOf(fill) + src; } //right else { src += String.valueOf(fill); } } return src; } }