Skip to content

Instantly share code, notes, and snippets.

@mrleolink
Last active November 27, 2016 09:00
Show Gist options
  • Save mrleolink/4c0225d2798f17663ab5 to your computer and use it in GitHub Desktop.
Save mrleolink/4c0225d2798f17663ab5 to your computer and use it in GitHub Desktop.
Explanation how to convert an int to hex string in Java use bitwise operations
public static String toHexString(int decimal) {
String codes = "0123456789ABCDEF";
StringBuilder builder = new StringBuilder(8);
builder.setLength(8);
for (int i = 7; i >= 0; i--) {
// E.g: let decimal = 229 -> its value when expressed in binary is 11100101
// And binary form of 0xF is 1111 (equals to ..00000001111)
// so AND operator between decimal 0xF basically takes 4 last bits of decimal because 11100101 & 00001111 = 00000101 = 5 in heximal
builder.setCharAt(i, codes.charAt(decimal & 0xF));
// decimal >> 4 basically removes 4 most right bits that already has been computed in previous line.
// so after first loop, decimal = ..000001110, and 00001110 & 00001111 = 1110 = E in heximal
// ========> result = 0xE5
decimal = decimal >> 4;
}
return builder.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment