Javaで16進数をASCIIに変換する方法
ここでは、JavaのHexをASCIIまたはその逆に変換する方法を示すJavaの例を示します。変換プロセスは、この式 ”
Hex ⇐⇒ Decimal ⇐⇒ ASCII
“によって異なります。
整数(10進数)は
Integer.toHexString
に続き、16進値に変換します。
-
Hex to ASCII – Hex値をペア形式で切り取り、基数に変換します
16 interger(decimal)
Integer.parseInt(hex、16)
、それをcharにキャストし直してください。
例
public class StringToHex{ public 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(); } public 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); } System.out.println("Decimal : " + temp.toString()); return sb.toString(); } public static void main(String[]args) { StringToHex strToHex = new StringToHex(); System.out.println("\n** ** ** ** ** Convert ASCII to Hex ** ** ** ** ** "); String str = "I Love Java!"; System.out.println("Original input : " + str); String hex = strToHex.convertStringToHex(str); System.out.println("Hex : " + hex); System.out.println("\n** ** ** ** ** Convert Hex to ASCII ** ** ** ** ** "); System.out.println("Hex : " + hex); System.out.println("ASCII : " + strToHex.convertHexToString(hex)); } }
出力
** ** ** ** ** Convert ASCII to Hex ** ** ** ** ** オリジナル入力:I Love Java! 16進数:49204c6f7665204a61766121 ** ** ** ** ** Convert Hex to ASCII ** ** ** ** ** Hex : 49204c6f7665204a61766121 Decimal : 7332761111181013274971189733 ASCII : I Love Java!
リファレンス
リンク://タグ/16進数/[16進]リンク://タグ/java/[java]