2016-06-11 99 views

回答

3

使用Integer類和radix參數,並從同一個類toHexString

Integer.toHexString(Integer.parseInt("-22EEVX", 36)); 

對於base10它更短(省略基數參數,假設10):

Integer.toHexString(Integer.parseInt("-22")); 
+0

謝謝@krzyk,但它給Integer.toHexString(Integer.parseInt(「 - 22EEVX」))錯誤爲'java.lang.NumberFormatException : – subodh

+0

@subodh因爲你使用base10版本來解析base36字符串。使用第一個代碼片段與'36' –

+0

感謝噸最簡單的方法,如果我需要回到實際的字符串有無論如何如上面或我需要轉換字節字節? – subodh

-1

如果你想在base36任何字符串編碼和解碼它可能對你有用。若要在基數10中使用它,請將以下代碼中的所有36替換爲10.

import java.math.BigInteger; 

public class Base36 { 

public static void main(String[] args) { 
    String str = convertHexToBase36(toHex("8978675cyrhrtgdxfawW#$#[email protected]$#")); 
    System.out.println(str); 
    String back = convertBase36ToHex(str); 
    System.out.println(fromHex(back)); 

} 

public static String fromHex(String hex) { 
    StringBuilder output = new StringBuilder(); 
    for (int i = 0; i < hex.length(); i += 2) { 
     String str = hex.substring(i, i + 2); 
     output.append((char) Integer.parseInt(str, 16)); 
    } 
    return output.toString(); 
} 

public static String convertHexToBase36(String hex) { 
    BigInteger big = new BigInteger(hex, 16); 
    StringBuilder sb = new StringBuilder(big.toString(36)); 
    return sb.reverse().toString(); 
} 

public static String convertBase36ToHex(String b36) { 
    StringBuilder sb = new StringBuilder(b36); 
    BigInteger base = new BigInteger(sb.reverse().toString(), 36); 
    return base.toString(16); 
} 

public static String toHex(String arg) { 
    return String.format("%040x", new BigInteger(1, arg.getBytes())); 
} 
} 
相關問題