I have an int number as 1238, when I convert to hex string with Integer.toHexString function, it will return me 4d6. Is there any possible way that I can format so it will return me 04d6 ? It would be great if you can provide solution for general case, not this specific case. Thank you.
Asked
Active
Viewed 2,912 times
-2
-
Whats wrong with triggering "0" + Integer.toHexString() ? And just to be precise: I would suggest to use "0x" as prefix - "0" is typically the prefix for OCTAL numbers; not hex. – GhostCat Mar 31 '15 at 13:39
-
This is an excellent problem to use as a learning experience. Work it out on your own. (There are about 20 different ways to handle it, so it should not be too hard to find one.) – Hot Licks Mar 31 '15 at 13:40
-
This post shows how to do this for 2 digits: http://stackoverflow.com/questions/8689526/integer-to-two-digits-hex-in-java That's easy to extend to 4 digits – Erwin Bolwidt Mar 31 '15 at 13:51
2 Answers
3
It would be great if you can provide solution for general case, not this specific case
This is a quick solution that will add a left 0 in the case the hex string length is not a multiple of 2.
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(myInt));
if (sb.length() % 2 > 0) {
sb.insert(0, '0'); // pad with leading zero if needed
}
String hex = sb.toString();

Drakes
- 23,254
- 3
- 51
- 94
3
System.out.println(String.format("%04x",1238)); -> "04d6"
System.out.println(String.format("%#04x",1238)); -> "0x4d6"

Robert
- 39,162
- 17
- 99
- 152
-
-
-
What I mean is, your solution is clever, but only for a small integer like 1238, not, say, 123899 – Drakes Mar 31 '15 at 22:35
-
It just solves the problem described in the problem. Your solution solves a problem never mentioned in the question. You don't know if the original problem is really "string length is not a multiple of 2" as the question does not mention it. – Robert Apr 01 '15 at 07:29
-
Te be fair, he first gives a specific example, but then states "It would be great if you can provide solution for general case, not this specific case". I was trying to address his latter requirement. – Drakes Apr 01 '15 at 07:57