简体   繁体   中英

How to convert int array to base64 string in Java?

How do I convert this array:

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

To this string?

String base64Encoded = "6ZoYxCjLONXyYIU2eJIuAw==";

Usage:

String base64Encoded  = ConvertToBase64(int[] ints);

(I'm asking this questions because byte in Java is signed, but byte in C# is unsigned)

The problem can be broken down into 2 simple steps: 1. Convert the int array to a byte array. 2. Encode the byte array to base4.

Here's one way to do that:

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

A more old school approach:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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