2011-10-02 612 views
1

一個UUID在「b2f0da40ec2c11e00000242d50cf1fbf」的形式進行了改造(參見下面的代碼段)爲十六進制的字符串作爲6232663064613430656332633131653030303030323432643530636631666266.我想編寫一個反向常規,拿回來的原始格式,如「b2f0 ...」,但很難這樣做,有什麼幫助?轉換UUID以十六進制字符串,反之亦然

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

什麼你的意思做你當前的代碼有什麼問題? –

+0

[使用Java將十六進制轉儲的字符串表示形式轉換爲字節數組]的可能的副本(http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-使用java編碼) – phihag

+0

原始格式的意思是這樣的:b2f0da40ec2c11e00000242d50cf1fbf。 – Oliver

回答

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

它打印:

input: 6232663064613430656332633131653030303030323432643530636631666266 
result: b2f0da40ec2c11e00000242d50cf1fbf 
2

在這裏你去: 「原始格式」

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); 
    } 
} 
相關問題