Decode an Encoded Base 64 String to ASCII String
Prerequisite : What is base64 Encoding and why we encode strings to base64 format
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 write.geeksforgeeks.org or mail your article to email@example.com. 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.