Bin
The Bin Type provides functions for manipulating binary data.
This Type is a crucial tool in scenarios where direct and efficient manipulation of raw binary data is required, making it highly valuable in fields such as data processing, network communication, cryptography, and file handling.
Binary data manipulation
The Bin Type provides tools to work with binary data. This includes converting data between formats like Base64 and hexadecimal, joining binary sequences together, and handling binary streams. It is especially useful for tasks that need advanced binary data changes, such as encoding and decoding in communication systems, or converting data to and from a format that external systems can understand.
Combining binary values
In the example below, the Bin.zeroes(10) function creates a binary value consisting of 10 zero bytes, and Bin.zeroes(20) generates a binary value with 20 zero bytes. The Bin.concat(...) function combines two binary values.
After concatenation, you can use the Bin.size(b) function to determine the size of the resulting binary value b.
// Create a binary value with 10 zero bytes using the zeroes method.
let b = Bin.concat(Bin.zeroes(10), Bin.zeroes(20))
// Check if the size of the concatenated binary value is 30 bytes.
Bin.size(b) === 30Decoding Base64 to binary
The code below successfully converts a valid Base64 encoded string, which represents Hi, Mom!, into a binary value. The code then verifies that the size of this binary value is 7 bytes, and encodes the binary value back into Base64 to confirm the correctness of the operations.
// Convert a valid Base64 encoded string to a binary value.
// The string "SGksIE1vbQ==" is "Hi, Mom!" in Base64.
let b = Bin.fromBase64("SGksIE1vbQ==")
// Check if the size of the binary value is 7 bytes.
Bin.size(b) === 7
// Encode the binary value back to Base64 to verify correctness.
Base64.encode(b) === "SGksIE1vbQ=="The code snippet below attempts to create a binary value from an invalid Base64 string, which results in an error.
Bin.fromBase64("`_O>") // throwsHexadecimal to binary conversion
The example below demonstrates how to convert hexadecimal strings to binary values.
The first snippet successfully converts a valid hexadecimal string aabbcc into a binary value. The size function verifies that the size of this binary value is 3 bytes. To verify the value is correct, you can encode the binary value to Base64.
// Convert a valid hexadecimal string "aabbcc" to a binary value.
let b = Bin.fromHex("aabbcc")
// Check if the size of the binary value is 3 bytes.
Bin.size(b) === 3
// Encode the binary value to Base64 to verify correctness.
let encodedOutput = Base64.encode(b);In the above code snippet, encodedOutput equals qrvM.
The code below attempts to convert an invalid hexadecimal string foo into a binary value, which results in an error, illustrating error handling in such conversions.
// Attempt to create a binary value from an invalid hexadecimal string, which throws an error.
Bin.fromHex("foo") // throwsData conversion and encoding
The Bin Type provides methods to convert strings to UTF-8 encoded binary data and vice versa, including functions to handle hexadecimal and Base64 encoded data. This is particularly useful in web development and network programming, where data often must be encoded and transmitted over various communication protocols.
// Simulate a hexadecimal string from a network request or file.
const hexData = "aabbcc";
try {
// Attempt to convert the hex data to binary.
// This is useful when the data is transmitted in a compact hex format.
const binaryData = Bin.fromHex(hexData);
// Calculate the size of the binary data.
// This is important for validating the data integrity and expected format.
const binarySize = Bin.size(binaryData);
// Check if the size of the binary data matches the expected size (3 bytes in this case).
// This verification step is crucial in scenarios where data size matters, such as in protocol compliance.
if (binarySize === 3) {
// If the size is correct, re-encode the data to Base64 for secure transmission.
// Base64 is commonly used in web applications for encoding binary data into a string format.
const base64Encoded = Base64.encode(binaryData);
// Log or transmit the Base64 encoded data.
console.log("Base64 Encoded Data:", base64Encoded);
} else {
// Log an error or handle the case where the binary data size is unexpected.
console.error("Unexpected binary data size.");
}
} catch (error) {
// Handle cases where the hex data is invalid and cannot be converted to binary.
// This is important for robust error handling in data processing pipelines.
console.error("Failed to convert hex to binary:", error.message);
}The example demonstrates transforming data from one format (hexadecimal) to another (binary and then Base64), which is common in data processing and communication systems.
Determining binary value emptiness
This code sample demonstrates how to use the Bin.isEmpty function to determine if a binary value is empty.
It covers three scenarios:
- It checks if a null binary value is regarded as empty, returning true.
- It verifies if a binary value with zero bytes is considered empty, which also results in true.
- Finally, the code checks if a binary value containing non-zero bytes (in this case,
10zero bytes) is considered not empty, correctly returningfalse.
// Check if a null binary value is considered empty.
Bin.isEmpty(null) === true
// Check if a binary value with zero bytes is considered empty.
Bin.isEmpty(Bin.zeroes(0)) === true
// Check if a binary value with non-zero bytes is considered not empty.
Bin.isEmpty(Bin.zeroes(10)) === falseThis example illustrates how you can use Bin.isEmpty to assess the emptiness of binary values in different contexts.
Comparing binary values
This section provides examples that illustrates how to use the Bin.isSame function to compare different binary values, and includes various comparisons to demonstrate the function's capability.
Check if two null binary values are considered the same.
// Check if two null binary values are the same.
Bin.isSame(null, null); // trueCompare a null binary value with a zero-byte binary value.
// Compare a null binary value with a zero-byte binary value.
Bin.isSame(null, Bin.zeroes(0)); // falseCompare two zero-byte binary values.
// Compare two zero-byte binary values.
Bin.isSame(Bin.zeroes(0), Bin.zeroes(0)); // trueCompare two binary values, each with 10 bytes.
// Compare two 10-byte binary values.
Bin.isSame(Bin.zeroes(10), Bin.zeroes(10)); // trueCompare binary values of different sizes (10 bytes and 20 bytes).
// Compare binary values of different sizes (10 bytes and 20 bytes).
Bin.isSame(Bin.zeroes(10), Bin.zeroes(20)); // falseThis sequence effectively demonstrates the versatility of Bin.isSame in determining the equivalence of binary values under various conditions.
Handling UTF-8 strings in binary format
This section focuses on demonstrating the use of the Bin Type to handle UTF-8 strings in binary format. It includes several examples to show how these functions work.
Wrap a null value with Bin.wrap and confirm that the result is null.
Bin.wrap(null) == null;Read a UTF-8 string from a null binary value using Bin.readUtf8String, which results in null.
// Read a UTF-8 string from a null binary value, resulting in null.
Bin.readUtf8String(null) == null;Create an empty binary value from an empty string and verify that its size is 0 bytes.
// Create an empty binary value from an empty string.
let b = Bin.wrap("");
// Verify that the binary value has a size of 0 bytes.
Bin.size(b) === 0;Read back the empty string from the binary value to ensure correctness.
// Read the empty string back from the binary value.
Bin.readUtf8String(b) === "";Create a binary value from the string hi, mom and verify its size as 7 bytes.
// Create a binary value from the string "hi, mom".
let b = Bin.wrap("hi, mom");
// Verify that the binary value has a size of 7 bytes.
Bin.size(b) === 7;Read the string hi, mom back from the binary value to confirm the accurate conversion between the string and its binary representation.
// Read the string "hi, mom" back from the binary value.
Bin.readUtf8String(b) === "hi, mom"This code sample illustrates the process of wrapping strings into binary values and reading UTF-8 strings from binary values, demonstrating the functionality of the wrap and readUtf8String functions in various scenarios.
Generating zero byte binary values
This section presents an example that shows how to generate and work with binary values containing zero bytes.
The process is outlined in three steps:
- Creation of a binary value containing 4 zero bytes using the
Bin.zeroesfunction. - Verification that the size of the created binary value is
4bytes, ensuring the function worked as expected. - Encoding of the binary value into a Base64 format to provide further verification of its correctness.
// Create a binary value with 4 zero bytes.
let b = Bin.zeroes(4);
// Verify the size of the binary value is 4 bytes.
Bin.size(b) === 4;
// Encode the binary value to Base64 for verification.
Base64.encode(b) === "AAAAAA==";This sample serves as a practical illustration of how to create and verify zero byte binary values, emphasizing the accuracy of the Bin.zeroes function in generating binary values.
Base64 encoding and decoding
This example showcases the Bin Type's utility in encoding and decoding operations. The process involves wrapping a string into a binary format, encoding it into Base64, and then decoding it back to its original form. This is a common technique in data transmission and storage where binary data must be converted into a text-based format.
// Encoding a string into Base64.
let originalString = "Hello World";
let encodedData = Base64.encode(Bin.wrap(originalString));
// Decoding the Base64 back to the original string.
let decodedData = Bin.readUtf8String(Base64.decode(encodedData));The Bin Type is a powerful and flexible tool for handling binary data across various applications and programming environments. Its extensive functionality for data manipulation, conversion, and encoding makes it indispensable in many areas of software development, particularly those involving complex data handling and high-performance requirements. Whether it's for file processing, network communication, cryptography, or cross-language software integration, the Bin Type provides a solid foundation for developers to efficiently and effectively manage binary data.