16進符号化文字への変換

1317 ワード

import java.io.UnsupportedEncodingException;

public class Hex2Char {
	public static void main(String[] args) throws UnsupportedEncodingException {
		/*
		* ¤  ISO8859-1 A4, 10100100 
		*  int  10100100 -> 164 ,
		*  byte  10100100 -> 11011100 -> -92
		*/
		int encoding = Integer.parseInt("A4", 16);
		System.out.println(Integer.toBinaryString(encoding));//10100100
		System.out.println(encoding);//164
		System.out.println((byte) encoding);//-92
		byte[] b = new byte[] { (byte) encoding };
		System.out.println(new String(b, "ISO8859-1"));// ¤ 

		/*
		 * ¤ GBK A1E8, 1010000111101000 
		 */
		encoding = Integer.parseInt("A1E8", 16);
		System.out.println(Integer.toBinaryString(encoding));//1010000111101000
		b = new byte[2];
		// 
		b[0] = (byte) (encoding >> 8);
		// 
		b[1] = (byte) (encoding & 0x0FF);
		System.out.println(byte2Hex(b[0]) + byte2Hex(b[1]));//A1E8
		System.out.println(new String(b, "GBK"));// ¤ 
	}

	private static String byte2Hex(byte value) {
		return Integer.toHexString(value & 0x00FF | 0xFF00).toUpperCase().substring(2, 4);
	}
}