How to convert string to byte array in TypeScript

1 Answer

0 votes
const str: string = "TypeScript";

// Convert string to byte array
const encoder: TextEncoder = new TextEncoder();
const byteArray: Uint8Array<ArrayBufferLike> = encoder.encode(str);

console.log(byteArray);

const byteArray_length: number = byteArray.length;
for (let i = 0; i < byteArray_length; i++) {
    console.log(byteArray[i]);
}

 
 
/*
run:
 
Uint8Array: {
  "0": 84,
  "1": 121,
  "2": 112,
  "3": 101,
  "4": 83,
  "5": 99,
  "6": 114,
  "7": 105,
  "8": 112,
  "9": 116
} 
84 
121 
112 
101 
83 
99 
114 
105 
112 
116 
 
*/

 



answered Mar 10, 2025 by avibootz
...