Skip to content

JavaScript string to byte array | Convert to Example code

  • by

How to convert a string in byteArray using JavaScript?

JavaScript Strings are stored in UTF-16. To get UTF-8, you’ll have to convert the String yourself.

JavaScript string to byte array example

HTML example code.

<!DOCTYPE HTML> 
<html> 
<body> 

	<script>
		var str = "Hello";
		var bytes = []; 
		var bytesv2 = []; 

		for (var i = 0; i < str.length; ++i) {
			var code = str.charCodeAt(i);

			bytes = bytes.concat([code]);

			bytesv2 = bytesv2.concat([code & 0xff, code / 256 >>> 0]);
		}


		console.log('bytes', bytes.join(', '));


		console.log('bytesv2', bytesv2.join(', '));

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

Output:

convert JavaScript string to byte array

Do comment if you have any doubts and suggestions on this JS Array 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

Your email address will not be published. Required fields are marked *