简体   繁体   English

将UUID转换为十六进制字符串,反之亦然

[英]Convert UUID to hex string and vice versa

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? 格式为“ b2f0da40ec2c11e00000242d50cf1fbf”的UUID已转换(参见下面的代码段)为十六进制字符串,如62326630646134306563326331316530303030303234326326435435366366666666666.6663666266。但是这样做很难,有什么帮助吗?

    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);
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

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM