com.github.downgoon.jresty.commons.security.HexCodec Maven / Gradle / Ivy
The newest version!
package com.github.downgoon.jresty.commons.security;
import java.io.ByteArrayOutputStream;
/**
* @author liwei
* @since 2008-08-05
* */
public class HexCodec {
public static String hexUpperAscii(byte[] data) {
return byte2HexFormat(data, 16, Configuration.byte2HexUpper,Configuration.byte2ASCII);
}
public static String hexLowerAscii(byte[] data) {
return byte2HexFormat(data, 16, Configuration.byte2HexLower,Configuration.byte2ASCII);
}
public static String hexUpperAscii(byte[] data,int width) {
return byte2HexFormat(data, width, Configuration.byte2HexUpper,Configuration.byte2ASCII);
}
public static String hexLowerAscii(byte[] data,int width) {
return byte2HexFormat(data, width, Configuration.byte2HexLower,Configuration.byte2ASCII);
}
/** 将byte[]数据以十六进制的形式显示,显示格式仿照UltraEdit*/
private static String byte2HexFormat(byte[] data,int width,
IByte2String hexPartitionMethod,IByte2String strPartitionMethod)
{
StringBuffer sb = new StringBuffer();
//表头
for(int i=0;i15) {
throw new IllegalArgumentException("输入参数"+high+","+lower+"都必须控制在范围[0,15]内");
}
return (byte)(high << 4 | lower);
}
/** 各个Byte之间的分割符号*/
static final String DELIMITER = " ";
/** Hex显示和字符显示区域分割符*/
static final String PARTITION = ";";
static IByte2String byte2HexUpper = new Byte2HexUpper();
static IByte2String byte2HexLower = new Byte2HexLower();
static IByte2String byte2ASCII = new Byte2ASCII();
}
static interface IByte2String {
public String byte2String(byte b);
}
static class Byte2HexUpper implements IByte2String {
public String byte2String(byte b) {
int high = 0x0F & b>>4;
int low = 0x0F & b;
return new String(new char[] {Configuration.HEX_UPPER_CASE[high],
Configuration.HEX_UPPER_CASE[low]});
}
}
static class Byte2HexLower implements IByte2String {
public String byte2String(byte b) {
int high = 0x0F & b>>4;
int low = 0x0F & b;
return new String(new char[] {Configuration.HEX_LOWER_CASE[high],
Configuration.HEX_LOWER_CASE[low]});
}
}
static class Byte2ASCII implements IByte2String {
private final String INVISIBLE_SUBSTITUTION = ".";
public String byte2String(byte b) {
return (Character.isWhitespace(b) || Character.isLetterOrDigit(b)) ? new String(new byte[]{b}) : INVISIBLE_SUBSTITUTION;
}
}
}