Skip to content

Instantly share code, notes, and snippets.

@namchuai
Last active August 21, 2017 18:38
Show Gist options
  • Save namchuai/e186f7fc14aedf233d490ecb9c62f8ad to your computer and use it in GitHub Desktop.
Save namchuai/e186f7fc14aedf233d490ecb9c62f8ad to your computer and use it in GitHub Desktop.
/**
* Created by namchuai on 8/21/17.
* Use to convert from Unicode code point to UTF-16
*/
public class Converter {
private static final int BASE_HEX = 0x10000;
private static int mHexInput = 0x9FFFF;
public static void main(String[] args) {
int minusResult = mHexInput - BASE_HEX;
System.out.println("Minus result: " + Integer.toHexString(minusResult).toUpperCase());
int charNumOfBinary = 20;
String binaryString = Integer.toBinaryString(minusResult);
while (binaryString.length() < charNumOfBinary) {
binaryString = "0" + binaryString;
}
char[] binaryChar = binaryString.toCharArray();
System.out.print("Minus binary: ");
for (int i = 0; i < binaryChar.length; i++) {
if (i != 0 && i % 4 == 0) {
System.out.print(" ");
}
System.out.print(binaryChar[i]);
}
System.out.println("");
final int mid = binaryString.length() / 2;
String[] parts = {binaryString.substring(0, mid), binaryString.substring(mid)};
if (parts[0].length() < 10) {
parts[0] = "00" + parts[0];
}
if (parts[1].length() < 10) {
parts[1] = "00" + parts[1];
}
System.out.println(parts[0]);
System.out.println(parts[1]);
String highBinary = "110110" + parts[0];
String lowBinary = "110111" + parts[1];
System.out.println(highBinary);
System.out.println(lowBinary);
int highDecimal = Integer.parseInt(highBinary, 2);
String highHexStr = Integer.toString(highDecimal, 16).toUpperCase();
int lowDecimal = Integer.parseInt(lowBinary, 2);
String lowHexStr = Integer.toString(lowDecimal, 16).toUpperCase();
System.out.println("High hex: " + highHexStr);
System.out.println("Low hex: " + lowHexStr);
System.out.println("Final: \\u" + highHexStr + "\\u" + lowHexStr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment