0

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)

0

1 Answer 1

10

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

Sign up to request clarification or add additional context in comments.

6 Comments

Please Provide Explanation To Your Answer!
@shmosel: won't the int get converted to a signed byte in your examples? That would generate a different string. Please see my requirements.
@JohnB You haven't posted any requirement, just a sample input and output, which my solution achieves.
@shmosel: your code converted my int array to a signed byte array. (see the comment I added above) My int array has unsigned values. Your code will render a different base64 string than what I specified in my question. Did you test this code?
@JohnB There's nothing wrong with signed bytes; bytes are always signed in Java. Whether the narrowing conversion from int to byte is the correct interpretation of your data depends on what your data represents. Since you have yet to specify that, I took a guess and verified the result by testing. I guess it's my turn to ask: did you test this code?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.