Decode an Encoded Base 64 String to ASCII String | JavaScript Program to decode a base64 Encoded String back to ASCII String ; char_set = " ABCDEFGHIJKLMNOPQRSTUVWXYZ ▁ abcdefghijklmnopqrstuvwxyz0123456789 + / " ; stores the bitstream . ; count_bits stores current number of bits in num . ; selects 4 characters from encoded String at a time . find the position of each encoded character in char_set and stores in num . ; make space for 6 bits . ; encoded [ i + j ] = ' E ' , ' E ' - ' A ' = 5 ' E ' has 5 th position in char_set . ; encoded [ i + j ] = ' e ' , ' e ' - ' a ' = 5 , 5 + 26 = 31 , ' e ' has 31 st position in char_set . ; encoded [ i + j ] = '8' , '8' - '0' = 8 8 + 52 = 60 , '8' has 60 th position in char_set . ; ' + ' occurs in 62 nd position in char_set . ; ' / ' occurs in 63 rd position in char_set . ; ( str [ i + j ] == ' = ' ) remove 2 bits to delete appended bits during encoding . ; 255 in binary is 11111111 ; Driver code ; Do not count last null character .
let SIZE = 100 ; function base64Decoder ( encoded , len_str ) { let decoded_String ; decoded_String = new Array ( SIZE ) ; let i , j , k = 0 ; let num = 0 ; let count_bits = 0 ; for ( i = 0 ; i < len_str ; i += 4 ) { num = 0 ; count_bits = 0 ; for ( j = 0 ; j < 4 ; j ++ ) { if ( encoded [ i + j ] != ' ' ) { num = num << 6 ; count_bits += 6 ; } if ( encoded [ i + j ] . charCodeAt ( 0 ) >= ' ' . charCodeAt ( 0 ) && encoded [ i + j ] . charCodeAt ( 0 ) <= ' ' . charCodeAt ( 0 ) ) num = num | ( encoded [ i + j ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) ; else if ( encoded [ i + j ] . charCodeAt ( 0 ) >= ' ' . charCodeAt ( 0 ) && encoded [ i + j ] . charCodeAt ( 0 ) <= ' ' . charCodeAt ( 0 ) ) num = num | ( encoded [ i + j ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) + 26 ) ; else if ( encoded [ i + j ] . charCodeAt ( 0 ) >= ' ' . charCodeAt ( 0 ) && encoded [ i + j ] . charCodeAt ( 0 ) <= ' ' . charCodeAt ( 0 ) ) num = num | ( encoded [ i + j ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) + 52 ) ; else if ( encoded [ i + j ] == ' ' ) num = num | 62 ; else if ( encoded [ i + j ] == ' ' ) num = num | 63 ; else { num = num >> 2 ; count_bits -= 2 ; } } while ( count_bits != 0 ) { count_bits -= 8 ; decoded_String [ k ++ ] = String . fromCharCode ( ( num >> count_bits ) & 255 ) ; } } return ( decoded_String ) ; } let encoded_String = " " . split ( " " ) ; let len_str = encoded_String . length ; len_str -= 1 ; document . write ( " " + ( encoded_String ) . join ( " " ) + " " ) ; document . write ( " " + base64Decoder ( encoded_String , len_str ) . join ( " " ) + " " ) ;