function bx
bx(hex: string): ArrayBuffer

A method that accepts a string containing hex encoded buffer. The string will be stripped of any non-hexadecimal symbols (eg: [^0-9-a-f]) and if the resulting string has even length then it's used as new Uint8Array(value).buffer or otherwise throws a TypeError.

Examples

Example 1

import { assertEquals } from "@std/assert";

// Using spaces to separate bytes
const HEADER = bx('00 ff 00 ff');
assertEquals(new Uint8Array(HEADER), new Uint8Array([0x00, 0xff, 0x00, 0xff]));

Example 2

import { assertEquals } from "@std/assert";

// Using underscores, dashes and other symbols to separate bytes
const SYNC1 = bx('00ff00ff_b4_01020304');
assertEquals(new Uint8Array(SYNC1), new Uint8Array([0x00,0xff,0x00,0xff,0xb4,0x01,0x02,0x03,0x04]));

Example 3

import { assertEquals, assertThrows } from "@std/assert";

// Empty string will return an empty ArrayBuffer
const ZEROLENGTH = bx('');
assertEquals(ZEROLENGTH.byteLength, 0);

// Only empty strings yield empty ArrayBuffer otherwise it throws
assertThrows(() => bx('          '), TypeError);

Example 4

import { assertThrows } from "@std/assert";
// Odd number of hex characters will throw a TypeError
assertThrows(() => bx('0 0 0'), TypeError);

Example 5

import { assertThrows } from "@std/assert";
// Each byte must be represented by two characters
assertThrows(() => bx('f2-00_0_00'), TypeError);

Parameters

hex: string

The string containing hex encoded data

Return Type

ArrayBuffer

An ArrayBuffer containing that data.