While working on a TypeScript project, I had to send user details over the network. The user data had to be sent in a byte format instead of plain strings. I had to convert strings to byte arrays in TypeScript for this requirement.
In this tutorial, I will explain how to convert a string to a byte array in TypeScript. There are different methods to do this; I will show you each method with examples.
Strings and Byte Arrays in TypeScript
Let me first explain what strings and byte arrays are in TypeScript.
- A string is a sequence of characters, such as “Hello, John!” or “123 Main St, New York, NY 10001”.
- A byte array is an array of integers, where each integer represents a single byte (8 bits) of data.
Converting a string to a byte array allows us to work with the raw binary representation of the string, which is essential for various scenarios like data transmission or cryptographic operations.
Check out: Convert a String to an Array in TypeScript
Convert a String to a Byte Array in TypeScript
Now, let me show you different methods to convert a string to a byte array in TypeScript.
Using the TextEncoder API
One of the easiest ways to convert a string to a byte array in TypeScript is by using the built-in TextEncoder API. Here’s an example:
const encoder = new TextEncoder();
const name = "John Doe";
const byteArray = encoder.encode(name);
console.log(byteArray);
// Output: Uint8Array(8) [74, 111, 104, 110, 32, 68, 111, 101]Output:

In this example, we create an instance of the TextEncoder class and use its encode method to convert the string “John Doe” to a byte array. The result byteArray is of type Uint8Array, which represents an array of unsigned 8-bit integers.
Check out: Convert an Object to an Array in TypeScript
Convert Character by Character
Another approach to convert a string to a byte array in TypeScript is by iterating over each character of the string and converting it to its corresponding ASCII code. Here’s an example:
function stringToByteArray(str: string): number[] {
const byteArray = [];
for (let i = 0; i < str.length; i++) {
byteArray.push(str.charCodeAt(i));
}
return byteArray;
}
const address = "123 Main St, New York, NY 10001";
const byteArray = stringToByteArray(address);
console.log(byteArray);
// Output: [49, 50, 51, 32, 77, 97, 105, 110, 32, 83, 116, 44, 32, 78, 101, 119, 32, 89, 111, 114, 107, 44, 32, 78, 89, 32, 49, 48, 48, 48, 49]Output:

In this example, we define a stringToByteArray function that takes a string as input and returns an array of numbers. Inside the function, we iterate over each character of the string using a for loop. For each character, we use the charCodeAt method to get its ASCII code and push it into the byteArray.
Handling Different Character Encodings
It’s important to consider the character encoding when converting a string to a byte array. Different encodings, such as UTF-8 or UTF-16, can represent characters using different byte sequences.
To handle different encodings, you can specify the desired encoding as an argument to the TextEncoder constructor or use a library like iconv-lite for more advanced encoding support.
Check out: Convert an Enum to an Array in TypeScript
First, install iconv-lite:
npm install iconv-liteThen import the library and execute the code below
import * as iconv from 'iconv-lite';
const name = "John Doe";
// Convert string to a byte array in UTF-16
const byteArray = iconv.encode(name, 'utf16le'); // For little-endian UTF-16
console.log(byteArray);
// Output: Uint16Array(12) [ 4a 00 6f 00 68 00 6e 00 20 00 44 00 6f 00 65 00]Output:

In this example, we specify the “utf-8” encoding when creating the TextEncoder instance. The resulting byte array represents the string “Michael Smith” encoded in UTF-16.
Real-World Example: Sending Data Over the Network
Let’s consider a real-world scenario where converting a string to a byte array is necessary. Suppose you’re building a client-server application that sends user information from the client to the server. You need to convert the user’s name and address to a byte array before sending it over the network.
interface UserData {
name: string;
address: string;
}
function sendUserData(userData: UserData): void {
const encoder = new TextEncoder();
const nameBytes = encoder.encode(userData.name);
const addressBytes = encoder.encode(userData.address);
// Combine the byte arrays
const dataBytes = new Uint8Array([...nameBytes, ...addressBytes]);
// Send the data over the network
// ...
}
const userData: UserData = {
name: "Emily Johnson",
address: "456 Elm St, Chicago, IL 60601"
};
sendUserData(userData);Output:

In this example, we define a UserData interface to represent the user’s information. The sendUserData function takes an UserData object as input and converts the name and address fields to byte arrays using the TextEncoder. We then combine the byte arrays into a single dataBytes array using the spread operator.
Finally, we can send the dataBytes over the network to the server for further processing.
Conclusion
I hope you understand the importance of converting a string to a byte array in TypeScript, especially when working with data encoding, encryption, or network communication. In this tutorial, we covered methods like the TextEncoder API and character-by-character conversion.
This data conversion is essential for handling raw binary data in various applications, from web apps to server-side scripts. By considering the character encoding and selecting the right approach, you can tackle string-to-byte array conversions confidently in your TypeScript projects.
You may also like to read:

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.