MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / encode

Method encode

src/main/java/com/thealgorithms/conversions/Base64.java:37–82  ·  view source on GitHub ↗

Encodes the given byte array to a Base64 encoded string. @param input the byte array to encode @return the Base64 encoded string @throws IllegalArgumentException if input is null

(byte[] input)

Source from the content-addressed store, hash-verified

35 * @throws IllegalArgumentException if input is null
36 */
37 public static String encode(byte[] input) {
38 if (input == null) {
39 throw new IllegalArgumentException("Input cannot be null");
40 }
41
42 if (input.length == 0) {
43 return "";
44 }
45
46 StringBuilder result = new StringBuilder();
47 int padding = 0;
48
49 // Process input in groups of 3 bytes
50 for (int i = 0; i < input.length; i += 3) {
51 // Get up to 3 bytes
52 int byte1 = input[i] & 0xFF;
53 int byte2 = (i + 1 < input.length) ? (input[i + 1] & 0xFF) : 0;
54 int byte3 = (i + 2 < input.length) ? (input[i + 2] & 0xFF) : 0;
55
56 // Calculate padding needed
57 if (i + 1 >= input.length) {
58 padding = 2;
59 } else if (i + 2 >= input.length) {
60 padding = 1;
61 }
62
63 // Combine 3 bytes into a 24-bit number
64 int combined = (byte1 << 16) | (byte2 << 8) | byte3;
65
66 // Extract four 6-bit groups
67 result.append(BASE64_CHARS.charAt((combined >> 18) & 0x3F));
68 result.append(BASE64_CHARS.charAt((combined >> 12) & 0x3F));
69 result.append(BASE64_CHARS.charAt((combined >> 6) & 0x3F));
70 result.append(BASE64_CHARS.charAt(combined & 0x3F));
71 }
72
73 // Replace padding characters
74 if (padding > 0) {
75 result.setLength(result.length() - padding);
76 for (int i = 0; i < padding; i++) {
77 result.append(PADDING_CHAR);
78 }
79 }
80
81 return result.toString();
82 }
83
84 /**
85 * Encodes the given string to a Base64 encoded string using UTF-8 encoding.

Callers 10

testBase64AlphabetMethod · 0.95
testStringEncodingMethod · 0.95
testByteArrayEncodingMethod · 0.95
testRoundTripEncodingMethod · 0.95
testBinaryDataMethod · 0.95
testNullInputEncodingMethod · 0.95
testLargeDataMethod · 0.95

Calls 3

lengthMethod · 0.80
appendMethod · 0.45
toStringMethod · 0.45

Tested by 10

testBase64AlphabetMethod · 0.76
testStringEncodingMethod · 0.76
testByteArrayEncodingMethod · 0.76
testRoundTripEncodingMethod · 0.76
testBinaryDataMethod · 0.76
testNullInputEncodingMethod · 0.76
testLargeDataMethod · 0.76