2

A UUID in the form of "b2f0da40ec2c11e00000242d50cf1fbf" has been transformed (see the following code segment) into a hex string as 6232663064613430656332633131653030303030323432643530636631666266. I want to code a reverse routine and get it back to the original format as in "b2f0...", but had a hard time to do so, any help?

    byte[] bytes = uuid.getBytes("UTF-8");

    StringBuilder hex = new StringBuilder(bytes.length* 2);
    Formatter fmt = new Formatter(hex);

    for (byte b : bytes)
        fmt.format("%x", b);
Oliver
  • 3,592
  • 8
  • 34
  • 37
  • What do you mean by "original format?" What's the problem with your current code? – Matt Ball Oct 02 '11 at 18:33
  • possible duplicate of [Convert a string representation of a hex dump to a byte array using Java?](http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java) – phihag Oct 02 '11 at 18:35
  • original format means something like this: b2f0da40ec2c11e00000242d50cf1fbf. – Oliver Oct 03 '11 at 02:54

2 Answers2

5
final String input = "6232663064613430656332633131653030303030323432643530636631666266";
System.out.println("input: " + input);
final StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length(); i += 2) {
    final String code = input.substring(i, i + 2);
    final int code2 = Integer.parseInt(code, 16);
    result.append((char)code2);

}
System.out.println("result: " + result);

It prints:

input: 6232663064613430656332633131653030303030323432643530636631666266
result: b2f0da40ec2c11e00000242d50cf1fbf
palacsint
  • 28,416
  • 10
  • 82
  • 109
2

Here you go:

import java.util.Formatter;

class Test {

    public static void main(String[] args) {
        String uuid = "b2f0da40ec2c11e00000242d50cf1fbf";
        byte[] bytes = uuid.getBytes();

        StringBuilder hex = new StringBuilder(bytes.length * 2);
        Formatter fmt = new Formatter(hex);

        for (byte b : bytes) {
            fmt.format("%x", b);
        }

        System.out.println(hex);

        /******** reverse the process *******/

        /**
         * group the bytes in couples
         * convert them to integers (base16)
         * and store them as bytes
         */
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
        }

        /**
         * build a string from the bytes
         */
        String original = new String(bytes);

        System.out.println(original);
    }
}
c00kiemon5ter
  • 16,994
  • 7
  • 46
  • 48