-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)
sbh
  • 65
  • 1
  • 9
  • 2
    Does this answer your question? [Converting A String To Hexadecimal In Java](https://stackoverflow.com/questions/923863/converting-a-string-to-hexadecimal-in-java) – alcatraz Jul 07 '21 at 17:12
  • 2
    Are you sure you want `1E 0F 03` and not `01 E0 F3`? – Pshemo Jul 07 '21 at 17:17

2 Answers2

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());
g00se
  • 3,207
  • 2
  • 5
  • 9
  • Did you know that you can append StringBuilder calls? So you can do `sb.insert(0, sep).insert(0, String.format("%02X", nybble));` – WJS Jul 07 '21 at 21:30
  • 1
    > 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. – g00se Jul 07 '21 at 23:17
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
WJS
  • 36,363
  • 4
  • 24
  • 39