![]() |
A Byte array is an array containing encoded data in the form of unsigned integers. It can’t be used directly. We have to decode it to get the meaning full data out of it. In this article, we will learn the conversion of a given byte array to a string of characters. Various approaches to convert byte array to string are as follows: Table of Content Approach 1: Using WebAPI TextDecoder.decode() MethodThe decode() method in TextDecoder API is used to take a stream of bytes as input and emit a stream of code points. The TextEncoder decode() method takes an ArrayBuffer containing the encoded data and options object and returns the original string (i.e. decoded string). Syntax: decoder.decode( buffer, options ); Parameters:
Return Value: It decodes the encoded input in the buffer and returns the decoded string. Example: In this example, we will create a string using the TextDecoder.decode() method from the Uint8Array instance.
Output JavaScript Approach 2: Using Buffer and toString() MethodsBuffers are instances of the Buffer class in Node.js. Buffers are designed to handle binary raw data. Syntax: let arr = new Buffer([16, 32, 48, 64]); The JavaScript Array toString() Method returns the string representation of the array elements Syntax: arr.toString(); Example: In this example, we have implemented the Buffer and toString() Methods for converting the byte array to a String.
Output JavaScript Approach 3: Using JavaScript string.fromCharCode() MethodThe JavaScript string.fromCharCode() method is used to create a string from the given sequence. Syntax: String.fromCharCode(n1, n2, ..., nX); Example: In this example, we will use String.fromCharCode() method to get the string output from a given byteArray.
Output GeeksforGeeks Approach 4: Using Base64 Encoding and DecodingConvert the byte array to a Base64 string using `btoa` after converting each byte to a character. Then, decode the Base64 string back to a normal string using `atob`. This method effectively handles the conversion via an intermediate Base64 representation. Example: The byteArrayToBase64 function converts a byte array to Base64 string using btoa, and base64ToString converts a Base64 string back to the original string using atob
Output Hello Approach 5: Using TextDecoder.decode() with Node.js BufferIn Node.js environments, you can also utilize the TextDecoder class along with Node.js Buffer to decode byte arrays into strings.
Output GeeksforGeeks Approach 6: Using the String constructor with Array.joinUsing the String constructor with Array.join converts a byte array to a string by mapping each byte to its character representation, joining them together into a single string using Array.join method. Example
Output String: Hello |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |