Install
$ npm install @k/encoding
UTF-8
For simple UTF-8 encoding and decoding, there are two exported methods.
import { utf8_to_ui8, ui8_to_utf8 } from '@k/encoding';
utf8_to_ui8('Hello'); // Uint8Array<48 65 6c 6c 6f>
ui8_to_utf8([ 0x48, 0x65, 0x6c, 0x6c, 0x6f ]); // "Hello"
Number Conversions
There are a large number of methods for converting various number types to/from byte arrays.
import { i32_to_ui8, ui8_to_i32 } from '@k/encoding';
i32_to_ui8(100000000); // [ 5, 245, 225, 0 ]
ui8_to_i32([ 5, 245, 225, 0 ]); // 100000000
The supported number types that can be converted are as follows:
- i8
- i16
- ui16
- i32
- ui32
- i64
- ui64
- f32
- f64
The main functions (like i32_to_ui8
) force all results to use a big-endian byte order. If you need to control the byte order yourself, see below.
Avoiding Copies
To avoid needless array allocations and copies, there are also direct-write versions of all the number _to_ui8
methods that will write directly into an array you pass in, as opposed to returning a new array. These methods instead return the new write index after the value is written (ie. if you write a 4-byte type, the return result will be the index you passed in, plus 4).
import { write_i32_as_ui8 } from '@k/encoding';
let index = 0;
const yourArray = [ ];
// Write the bytes for 100000000 into `yourArray`, starting at index 0
index = write_i32_as_ui8(100000000, yourArray, index);
Byte Order
If you need to check if the system uses little or big endian byte order, there are exported constants to tell you.
import { isLittleEndian, isBigEndian } from '@k/encoding';
All of the number conversion functions also have "forward" and "backward" versions (ie. i32_to_ui8
also has i32_to_ui8_forward
and i32_to_ui8_backward
counterparts). To use the systems byte order, use the "forward" methods, and to use the oposite, use the "backward" methods.