-3

I want to format string in hex in Java.

e.g. input: 123123, output: 1E 0F 03

Here is my code:

String.format("%02X", integer)
2
  • 2
    Does this answer your question? Converting A String To Hexadecimal In Java Commented Jul 7, 2021 at 17:12
  • 2
    Are you sure you want 1E 0F 03 and not 01 E0 F3? Commented Jul 7, 2021 at 17:17

2 Answers 2

1

Try something like:

        int n = 123123;
        StringBuilder sb = new StringBuilder();
        String sep = "";
        while (n > 0) {
            int nybble = n & 0xFF;
            sb.insert(0, sep);
            sb.insert(0, String.format("%02X", nybble));
            sep = " ";
            n >>>= 8;
        }
        System.out.println(sb.toString());
Sign up to request clarification or add additional context in comments.

2 Comments

Did you know that you can append StringBuilder calls? So you can do sb.insert(0, sep).insert(0, String.format("%02X", nybble));
> Did you know that you can append StringBuilder calls?< You mean chain calls. Yes, I did but I thought the code might be a bit clearer for not doing that in this particular case.
0

You could do it like this

  • convert the value to uppercase hex
  • prepend a "0" based on length
  • then split and rejoin (the regex splits on the zero width area after every two characters).
for (int val : new int[] { 123123, 122, 94392, 9200812 }) {
    String valStr = String.format("%X",val);
    valStr = (valStr.length() % 2 == 0 ? "" : "0") + valStr;
    String result = String.join(" ", valStr.split("(?<=\\G(..))"));
    System.out.printf("%7d = %10s = %s%n", val, valStr, result);
}

Prints

 123123 =     01E0F3 = 01 E0 F3
    122 =         7A = 7A
  94392 =     0170B8 = 01 70 B8
9200812 =     8C64AC = 8C 64 AC

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.