2017-05-18 151 views
0

如何轉換此陣:如何在Java中將int數組轉換爲base64字符串?

int[] ints = { 233, 154, 24, 196, 40, 203, 56, 213, 242, 96, 133, 54, 120, 146, 46, 3 }; 

爲了這個字符串?

String base64Encoded = "6ZoYxCjLONXyYIU2eJIuAw=="; 

用法:

String base64Encoded = ConvertToBase64(int[] ints); 

(我問這個問題,因爲byte在Java中籤名,但byte在C#是無符號數)

回答

5

的問題可以被打破分爲2個簡單步驟:1.將int數組轉換爲一個字節數組。 2.將字節數組編碼爲base4。

這裏有一個辦法做到這一點:

public static String convertToBase64(int[] ints) { 
    ByteBuffer buf = ByteBuffer.allocate(ints.length); 
    IntStream.of(ints).forEach(i -> buf.put((byte)i)); 
    return Base64.getEncoder().encodeToString(buf.array()); 
} 

一個更老派的做法:

public static String convertToBase64(int[] ints) { 
    byte[] bytes = new byte[ints.length]; 
    for (int i = 0; i < ints.length; i++) { 
     bytes[i] = (byte)ints[i]; 
    } 
    return Base64.getEncoder().encodeToString(bytes); 
} 

View running code on Ideone.com

+0

請提供解釋到答案! – Yahya

+0

@shmosel:在你的例子中'int'不會被轉換爲一個簽名的'byte'嗎?這會產生一個不同的字符串。請看我的要求。 – JohnB

+0

@JohnB您還沒有發佈任何要求,只是我的解決方案實現的示例輸入和輸出。 – shmosel

相關問題