Byte Array to Base64 JavaScript | Examples code

Use fromCharCode() and btoa() method to Byte array to base64 in JavaScript.

The fromCharCode() method converts Unicode values into characters. It is a static method of the String object. The btoa() method encodes a string in base-64.

Convert a bytes array to base64 String example

A function/program that converts an array of bytes (i.e.: an array of integers from 0 to 255), to base64.

<!DOCTYPE HTML> 
<html> 
<body> 

	<script>
		var arr = [
		"1101000",
		"1100101",
		"1101100",
		"1101100",
		"1101111",
		"100000",
		"1110111",
		"1101111",
		"1110010",
		"1101100",
		"1100100"
		];

		var encode = function(d,a,e,b,c,f){c="";for(a=e=b=0;a<4*d.length/3;f=b>>2*(++a&3)&63,c+=String.fromCharCode(f+71-(f<26?6:f<52?0:f<62?75:f^63?90:87))+(75==(a-1)%76?"\r\n":""))a&3^3&&(b=b<<8^d[e++]);for(;a++&3;)c+="=";return c};

		console.log(encode(arr)); 

	</script>
</body> 
</html>	

Output:

Convert a bytes array to base64 String example

Convert arrayBuffer to Base64 string Example

Convert received arrayBuffer value into Base64 encoded string and then we write a file using toBinary() function of CFML bypassing Base64 encoded string in it. Below is custom JavaScript function arrayBufferToBase64() to accomplish the requirement.

<!DOCTYPE HTML> 
<html> 
<body> 

	<script>
		var arr = [
		"1101000",
		"1100101",
		"1101100",
		"1101100",
		"1101111",
		"100000",
		"1110111",
		"1101111",
		"1110010",
		"1101100",
		"1100100"
		];

		function arrayBufferToBase64( buffer ) {
			var binary = '';
			var bytes = new Uint8Array( buffer );
			var len = bytes.byteLength;
			for (var i = 0; i < len; i++) {
				binary += String.fromCharCode( bytes[ i ] );
			}
			return window.btoa( binary );

		}

		console.log(arrayBufferToBase64(arr));

	</script>
</body> 
</html>		

Output:

Convert arrayBuffer to Base64 string Example

Do comment if you have any doubts and suggestions on this JS Array byte topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.