字符串转16进制码

public static String bedCardToEncode(String str) throws Exception {
		String hexString = "0123456789ABCDEF";
		// 根据编码获取字节数组
		byte[] bytes = str.getBytes("GBK");
		StringBuilder sb = new StringBuilder(bytes.length * 2);
		// 将字节数组中每个字节拆解成2位16进制整数
		for (int i = 0; i < bytes.length; i++) {
			sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
			sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
		}
		return sb.toString();
}

public static void main(String[] args) {

		try {
			System.out.println(bedCardToEncode("abcd-祖国万岁!"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
}

输出结果:

 616263642DD7E6B9FACDF2CBEAA3A1

你可能感兴趣的:(分享,java)