name:
src/main/js/formulas/engineering/BIN2HEX.ts
-rw-r--r--
2112
1import { NumException } from "../../errors/NumException";
2import { ValueException } from "../../errors/ValueException";
3import { SheetColumnRowKey } from "../../models/common/SheetColumnRowKey";
4import { Complex } from "../../models/common/Types";
5import { Converters } from "../../utils/Converters";
6import { AbstractFormula } from "../AbstractFormula";
7import { FormulaName } from "../FormulaName";
8
9export class BIN2HEX extends AbstractFormula {
10 static SELF: BIN2HEX = new BIN2HEX();
11 NAME = FormulaName.BIN2HEX;
12
13 internal(origin: SheetColumnRowKey, ...values: Array<Complex>) {
14 AbstractFormula.checkLengthBetween(values.length, 1, 2, this.NAME);
15 const signedBinaryNumber = Converters.first(this.collateralLookup(origin, values[0]));
16 let significantDigits = 10;
17 if (values.length === 2) {
18 significantDigits = Converters.toNumber(
19 Converters.first(this.collateralLookup(origin, values[1]))
20 );
21 }
22
23 if (typeof signedBinaryNumber === "boolean") {
24 throw new ValueException(
25 `Function BIN2HEX parameter 1 expects text values. But '${signedBinaryNumber}' is a boolean and cannot be coerced to a text.`
26 );
27 }
28 const n = Converters.toText(signedBinaryNumber);
29 if (!/^[01]{1,10}$/.test(n)) {
30 throw new NumException(`Input for BIN2HEX ('${n}') is not a valid binary representation.`);
31 }
32
33 if (n.length === 10 && n.substring(0, 1) === "1") {
34 return (1099511627264 + parseInt(n.substring(1), 2)).toString(16).toUpperCase();
35 }
36
37 if (significantDigits < 1 || significantDigits > 10) {
38 throw new NumException(
39 `Function BIN2HEX parameter 2 value is ${significantDigits}. Valid values are between 1 and 10 inclusive.`
40 );
41 }
42 significantDigits = Math.floor(significantDigits);
43 // Convert decimal number to hexadecimal
44 const result = parseInt(n.toString(), 2).toString(16).toUpperCase();
45 if (significantDigits === 10) {
46 return result;
47 }
48 let str = "";
49 for (let i = 0; i < significantDigits - result.length; i++) {
50 str += "0";
51 }
52 return str + result;
53 }
54}