DEV Community

Masui Masanori
Masui Masanori

Posted on

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

Intro

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.

Environments

  • Node.js ver.17.0.1
  • TypeScript 4.4.4

string <--> ArrayBuffer

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

main.page.ts

export function init(): void {
    const originalText = "こんにちは";
    const textBuffer = convertFromStringToBuffer(originalText);
    console.log(textBuffer);
    const convertedText = convertFromBufferToString(textBuffer);
    console.log(convertedText);
}
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

Results

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".

main.page.ts

export function init(): void {
...
    const originalNumber = 300.503;
    const numberBuffer = convertFromFloatToBuffer(originalNumber);
    console.log(numberBuffer);
    const convertedNumber = convertFromBufferToFloat(numberBuffer);
    console.log(convertedNumber);
}
...
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

Results

ArrayBuffer(4)
    byteLength: 4
    [[Prototype]]: ArrayBuffer
    [[Int8Array]]: Int8Array(4)
    [[Uint8Array]]: Uint8Array(4)
    [[Int16Array]]: Int16Array(2)
    [[Int32Array]]: Int32Array(1)
    [[ArrayBufferByteLength]]: 4
    [[ArrayBufferData]]: "0x0d1601a0c460"
300.50299072265625
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.

boolean

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

Discussion (0)