Base64 encoding is performed at sending node before transmitting bits over a network, and receiving node decodes that encoded data back to original ASCII string.
Base64 character set is
// 64 characters char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz0123456789+/"
Input : TUVO04= // (Encoded into base64 format) Output : MENON // (Decoded back to ASCII string) Input : Z2Vla3Nmb3JnZWVrcw== Output : geeksforgeeks
- Here each character in encoded string is considered to be made of 6 bits. We will take 4 characters each from Encoded String at one time i.e 4 * 6 = 24 bits. For each 4 characters of encoded string we will produce 3 characters of original string which will be of 8 bits each i.e 3 * 8 = 24 bits.
- Find their respective position in char_set and store it inside a variable (num) by using ‘|’ OR operator for storing bits and (LEFT – SHIFT) by 6 to make room for another 6 bits.
NOTE : We used ‘=’ in encoder to substitute for 2 missing bits, So here in decoder we have to reverse the process. Whenever we encounter a ‘=’ we have to delete 2 bits of num by using (RIGHT – SHIFT) by 2.
- After we have stored all the bits in num we will retrieve them in groups of 8, by using & operator with 255 (11111111), that will store the 8 bits from num and that will be our original character from ASCII string.
Encoded string : TUVO04= Decoded string : MENON
Time Complexity: O(N)
Space Complexity : O(1)
This article is contributed by Arshpreet Soodan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Return maximum occurring character in an input string
- Print all the duplicates in the input string
- Remove characters from the first string which are present in the second string
- Remove duplicates from a given string
- Print reverse of a string using recursion
- Write a program to print all permutations of a given string
- Divide a string in N equal parts
- Given a string, find its first non-repeating character
- Write a program to reverse an array or string
- Reverse words in a given string
- Find the smallest window in a string containing all characters of another string
- Lexicographic rank of a string
- An in-place algorithm for String Transformation
- Count words in a given string
- String matching where one string contains wildcard characters
Improved By : 29AjayKumar