阅读 154

十六进制工具包

解析十六进制用

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class HexUtil {    
// 字符串十六进制转byte
public static byte hexToByte(String inHex) {
    return (byte) Integer.parseInt(inHex, 16); 
}  
public static String byteToHex(byte b) { 
    String hex = Integer.toHexString(b & 0xFF);
    if (hex.length() < 2) { 
        hex = "0" + hex;  
    }      
    return hex; 
}
//字节数组转16进制 
public static String bytesToHex(byte[] bytes) {   
    StringBuffer sb = new StringBuffer();   
    for (int i = 0; i < bytes.length; i++) {   
        String hex = Integer.toHexString(bytes[i] & 0xFF);   
        if (hex.length() < 2) { 
            sb.append(0); 
        }      
        sb.append(hex);
    }     
    return sb.toString(); 
}   
//字节转Int
public static int byteToInt(byte b) {    
// Java 总是把 byte 当做有符处理;我们可以通过将其和 0xFF 进行二进制与得到它的无符值    
    return b & 0xFF;    
}   
// 字节数组转Int
public static int bytesToInt(byte[] ary) {    
    int value;   
    value = (int) ((ary[0] & 0xFF) | ((ary[1] << 8) & 0xFF00));   
    return value; 
}   
//十六进制转字节数组  
public static byte[] hexToByteArray(String inHex) { 
    int hexlen = inHex.length();    
    byte[] result;   
    if (hexlen % 2 == 1) {  
        // 奇数         
        hexlen++;   
        result = new byte[(hexlen / 2)];      
        inHex = "0" + inHex;   
    } else {     
        // 偶数      
        result = new byte[(hexlen / 2)]; 
    }       
    int j = 0;   
    for (int i = 0; i < hexlen; i += 2) {    
        result[j] = hexToByte(inHex.substring(i, i + 2));   
        j++;    
    }  
    return result;  
} 
//字节数组转UTF-8字符
public static String bytesToUTF8(byte[] bytes) throws UnsupportedEncodingException {  
    String str = new String(bytes, "UTF-8");     
    return str;   
}  
//字节求和转Hex
public static String bytesSumHex(byte[] bytes) {  
    long sum = 0;    
    for (byte b : bytes) {   
    sum += b;      
    }      
    return Long.toHexString(sum);  
}  
//十六进制字符串转高低位转换Byte数组
public static byte[] hexStringToHighLowConversionTwoBytes(String str) {    
    // 校验和要高低位转换     
    // 低位在前,高位在后   
    byte[] result = new byte[2];     
    byte[] bytes = hexToByteArray(str);   
    result[0] = bytes[bytes.length - 1];    
    if (bytes.length >= 2) {        
        result[1] = bytes[bytes.length - 2];    
    } else {        
        result[1] = 0x00;     
    }       
    return result; 
}}
复制代码
文章分类
后端
文章标签