Java 进制转换工具类

/**
 * 进制转换工具类
 * @author dell
 *
 */
public class HexadecimalUtil {
	
	/**
	 * 获得倒序二进制数据
	 * @param hexString
	 * @return
	 */
	public static String hexString2binaryString(String hexString) {
		if (hexString == null || hexString.length() % 2 != 0)
			return null;
		String bString = "", tmp;
		for (int i = 0; i < hexString.length(); i++) {
			tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
			bString += tmp.substring(tmp.length() - 4);
		}
		return reverseOrder(bString);
	}

	/**
	 * 将数据部分拆分成二进制
	 * @param bytes
	 * @param begin
	 * @param end
	 * @return
	 */
	public static String bytesToHex(byte[] bytes, int begin, int end) {
		StringBuilder hexBuilder = new StringBuilder(2 * (end - begin));
		for (int i = begin; i < end; i++) {
			hexBuilder.append(Character.forDigit((bytes[i] & 0xF0) >> 4, 16)); // 转化高四位
			hexBuilder.append(Character.forDigit((bytes[i] & 0x0F), 16)); // 转化低四位
			hexBuilder.append(' '); // 加一个空格将每个字节分隔开
		}
		return hexBuilder.toString().toUpperCase();
	}
	
	/**
	 * 接受数据 00 0A 4B 55
	 * 返回00001010 00001010 数组
	 * @param data
	 * @return
	 */
	public static String[] getDate(String data) {
		String[] datas = data.split(" ");
		String[] returnDatas = new String[50];
		for (int i = 0; i < datas.length; i++) {
			returnDatas[i] = hexString2binaryString(datas[i]);
		}
		return returnDatas;
	}
	
	/**
	 * 十六进制转十进制
	 * @param num
	 * @return
	 */
	public static Integer get10HexNum(String num){
		return Integer.parseInt(num.substring(0),16);
	}
	

	/**
	 * 倒序字符串
	 * @param old
	 * @return
	 */
	public static String reverseOrder(String old){
		return new StringBuffer(old).reverse().toString();
	} 
	
	public static void main(String arg[]) {
		/*String hexString = "0A AA 3B";
		System.out.println(hexString2binaryString(hexString));
		String[] r = getDate(hexString);
		System.out.println(r);
		System.out.println(reverseOrder("00111111"));*/
		String hex = "BBCC";
		Integer x = Integer.parseInt(hex.substring(0),16);//从第2个字符开始截取
		System.out.println(x);
	}
}

 

你可能感兴趣的:(java工具类)