DEV Community

Masui Masanori
Masui Masanori

Posted on

[TypeScript] Convert from TypeScript(JavaScript) data type to binary data


When I receive or send data between client side and server side in TypeScript, I convert data to JSON.
But sometime I have to convert to binary data to receive or send data.


  • Node.js ver.17.0.1
  • TypeScript 4.4.4

string <--> ArrayBuffer

I can convert string values by "TextDecoder" and "TextEncoder".

export function init(): void {
    const originalText = "こんにちは";
    const textBuffer = convertFromStringToBuffer(originalText);
    const convertedText = convertFromBufferToString(textBuffer);
function convertFromStringToBuffer(value: string): ArrayBuffer {
    // Encode with UTF-8
    const encoder = new TextEncoder();
    return encoder.encode(value);
function convertFromBufferToString(value: ArrayBuffer): string {
    // Decode with UTF-8
    const decoder = new TextDecoder();
    return decoder.decode(value);
Enter fullscreen mode Exit fullscreen mode


Uint8Array(15) [227, 129, 147, 227, 130, 147, 227, 129, 171, 227, 129, 161, 227, 129, 175, buffer: ArrayBuffer(15), byteLength: 15, byteOffset: 0, length: 15]
Enter fullscreen mode Exit fullscreen mode

number <--> ArrayBuffer

For converting number value to "ArrayBuffer", I can use "DataView".

export function init(): void {
    const originalNumber = 300.503;
    const numberBuffer = convertFromFloatToBuffer(originalNumber);
    const convertedNumber = convertFromBufferToFloat(numberBuffer);
function convertFromFloatToBuffer(value: number): ArrayBuffer {
    const buffer = new ArrayBuffer(4);
    const dataView = new DataView(buffer);
    dataView.setFloat32(0, value, true);
    return dataView.buffer;
function convertFromBufferToFloat(value: ArrayBuffer): number {
    const dataView = new DataView(value);
    return dataView.getFloat32(0, true);
Enter fullscreen mode Exit fullscreen mode


    byteLength: 4
    [[Prototype]]: ArrayBuffer
    [[Int8Array]]: Int8Array(4)
    [[Uint8Array]]: Uint8Array(4)
    [[Int16Array]]: Int16Array(2)
    [[Int32Array]]: Int32Array(1)
    [[ArrayBufferByteLength]]: 4
    [[ArrayBufferData]]: "0x0d1601a0c460"
Enter fullscreen mode Exit fullscreen mode

Little Endian

The third argument of "setFloat32" is Little Endian.
At least when I tried to connect with a C# application what converts data with "BitConverter", I had to use it.


"DataView" and "BitConverter" can't convert boolean value directly.
So I sent the values as "0" or "1".

Top comments (0)