ASCII、十六進位制、位元組陣列、字元陣列相互轉換
阿新 • • 發佈:2019-02-04
/** * 字串轉換為Ascii * @param value * @return */ public static String stringToASCII(String value) { StringBuffer sbu = new StringBuffer(); char[] chars = value.toCharArray(); for (int i = 0; i < chars.length; i++) { // if(i != chars.length - 1) // { // sbu.append((int)chars[i]).append(","); // } // else{ // } sbu.append((int)chars[i]); } return sbu.toString(); }
字串轉換為ASCII
/** * 字串轉換為十六進位制 * @param value * @return */ public static String convertStringToHex(String str) { char[] chars = str.toCharArray(); StringBuffer hex = new StringBuffer(); for (int i = 0; i < chars.length; i++) { hex.append(Integer.toHexString((int) chars[i])); } return hex.toString(); }
字串轉換為十六進位制
/** * 十六進位制轉換為字串 * @param value * @return */ public static String convertHexToString(String hex) { StringBuilder sb = new StringBuilder(); StringBuilder temp = new StringBuilder(); // 49204c6f7665204a617661 split into two characters 49, 20, 4c... for (int i = 0; i < hex.length() - 1; i += 2) { // grab the hex in pairs String output = hex.substring(i, (i + 2)); // convert hex to decimal int decimal = Integer.parseInt(output, 16); // convert the decimal to character sb.append((char) decimal); temp.append(decimal); } return sb.toString(); }
十六進位制轉換為字串
// char轉byte
public static byte[] getBytes (char[] chars) {
Charset cs = Charset.forName ("UTF-8");
CharBuffer cb = CharBuffer.allocate(chars.length);
cb.put(chars);
cb.flip();
ByteBuffer bb = cs.encode(cb);
return bb.array();
}
字元陣列轉換為位元組陣列
// byte轉char
public static char[] getChars(byte[] bytes) {
Charset cs = Charset.forName ("UTF-8");
ByteBuffer bb = ByteBuffer.allocate(bytes.length);
bb.put(bytes);
bb.flip();
CharBuffer cb = cs.decode(bb);
return cb.array();
}
位元組陣列轉換為字元陣列
// 十進位制轉化為十六進位制,結果為C8。
Integer.toHexString(200);
// 十六進位制轉化為十進位制,結果140。
Integer.parseInt("8C",16)