Skip to content

Instantly share code, notes, and snippets.

@akirad
Last active August 9, 2017 09:49
Show Gist options
  • Save akirad/f9279f6528c48bec2c470fa87cb00432 to your computer and use it in GitHub Desktop.
Save akirad/f9279f6528c48bec2c470fa87cb00432 to your computer and use it in GitHub Desktop.
A sample program to change bin to hex and hex to bin.
public class ChangeBinHex {
public static void main(String[] args) {
String str = "z";
String hexStr = binToHexString(str.getBytes());
System.out.println(hexStr); // 7a (0111 1100)
byte[] bytes = hexStrToBin(hexStr);
for (byte b : bytes) {
System.out.print(b + " "); // 122 (0111 1010) : Ascii Code of "z"
}
System.out.println();
String orgStr = new String(bytes);
System.out.println(orgStr); // z
}
private static String binToHexString(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
// I want to change as follows.
// 11000000 -> 00000000 00000000 00000000 11000000 ->C0
// If no "0xFF", b is treated as int and changed as follows.
// 11000000 -> 11111111 11111111 11111111 11000000 -> FF FF FF C0
String s = Integer.toHexString(0xFF & b);
if (s.length() == 1) {
hexString.append('0');
}
hexString.append(s);
}
return hexString.toString();
}
private static byte[] hexStrToBin(String hexStr) {
byte[] bin = new byte[hexStr.length() / 2];
try {
for (int i = 0; i < bin.length; i++) {
// Change a hex string to a numeric value(binary value).
// Ex. "3f" (‭0011 0011 ‭0110 0110‬‬) -> 63 (0011 1111)
bin[i] = (byte) Integer.parseInt(hexStr.substring(i * 2, i * 2 + 2), 16);
}
} catch (NumberFormatException e) {
System.err.println("Failed to change hex string to binary value");
System.exit(1);
}
return bin;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment