diff --git a/src/core/lib/Binary.mjs b/src/core/lib/Binary.mjs index 072000db4a..de003c7980 100644 --- a/src/core/lib/Binary.mjs +++ b/src/core/lib/Binary.mjs @@ -9,6 +9,7 @@ import Utils from "../Utils.mjs"; import OperationError from "../errors/OperationError.mjs"; +export const MAX_BINARY_PADDING = 65536; /** * Convert a byte array into a binary string. @@ -32,6 +33,10 @@ export function toBinary(data, delim="Space", padding=8) { if (data === undefined || data === null) throw new OperationError("Unable to convert to binary: Empty input data enocuntered"); + padding = Number(padding); + if (!Number.isFinite(padding) || padding < 0 || Math.round(padding) !== padding || padding > MAX_BINARY_PADDING) + throw new OperationError(`Byte length must be an integer between 0 and ${MAX_BINARY_PADDING}`); + delim = Utils.charRep(delim); let output = ""; @@ -77,4 +82,3 @@ export function fromBinary(data, delim="Space", byteLen=8) { } return output; } - diff --git a/src/core/operations/ToBinary.mjs b/src/core/operations/ToBinary.mjs index ba72a55bbc..0fb43b3c34 100644 --- a/src/core/operations/ToBinary.mjs +++ b/src/core/operations/ToBinary.mjs @@ -7,7 +7,7 @@ import Operation from "../Operation.mjs"; import Utils from "../Utils.mjs"; import {BIN_DELIM_OPTIONS} from "../lib/Delim.mjs"; -import {toBinary} from "../lib/Binary.mjs"; +import {MAX_BINARY_PADDING, toBinary} from "../lib/Binary.mjs"; /** * To Binary operation @@ -35,6 +35,8 @@ class ToBinary extends Operation { { "name": "Byte Length", "type": "number", + "min": 1, + "max": MAX_BINARY_PADDING, "value": 8 } ]; diff --git a/tests/operations/index.mjs b/tests/operations/index.mjs index c44270fdec..26b5f5eb9c 100644 --- a/tests/operations/index.mjs +++ b/tests/operations/index.mjs @@ -178,6 +178,7 @@ import "./tests/TakeNthBytes.mjs"; import "./tests/Template.mjs"; import "./tests/TextEncodingBruteForce.mjs"; import "./tests/TextIntegerConverter.mjs"; +import "./tests/ToBinary.mjs"; import "./tests/ToFromInsensitiveRegex.mjs"; import "./tests/TranslateDateTimeFormat.mjs"; import "./tests/Typex.mjs"; diff --git a/tests/operations/tests/ToBinary.mjs b/tests/operations/tests/ToBinary.mjs new file mode 100644 index 0000000000..3ac8dba105 --- /dev/null +++ b/tests/operations/tests/ToBinary.mjs @@ -0,0 +1,33 @@ +/** + * To Binary tests + * + * @author n1474335 [n1474335@gmail.com] + * @copyright Crown Copyright 2026 + * @license Apache-2.0 + */ +import TestRegister from "../../lib/TestRegister.mjs"; + +TestRegister.addTests([ + { + name: "To Binary: custom byte length", + input: "hello", + expectedOutput: "01101000 01100101 01101100 01101100 01101111", + recipeConfig: [ + { + "op": "To Binary", + "args": ["Space", 8] + } + ] + }, + { + name: "To Binary: byte length too large", + input: "hello", + expectedOutput: "Byte length must be an integer between 0 and 65536", + recipeConfig: [ + { + "op": "To Binary", + "args": ["Space", "8111111111111111111"] + } + ] + } +]);