javascript-binary-converter
Version:
A utility package to quickly handle and convert various Javascript binary objects
45 lines • 1.98 kB
JavaScript
import { integerToBinary, getBytesFromInteger, floatToBinary, bigIntegerToBinary, getDecimalBytesFromInteger } from "../utils/binary";
import { bigIntegerToHexaDecimal, integerToHexaDecimal, floatToHexString, hexStringToFloat, hexStringToInteger } from "../utils/hex";
import { isBigInt, isFloat } from "../utils/number";
/**
* This class handles any number|bigint, in any type Number notation(decimal,octal,hex,binary)
*/
export default class NumberConverter {
constructor(original) {
this.original = original;
}
toBinary({ precision = 'SINGLE' } = {}) {
if (isBigInt(this.original))
return bigIntegerToBinary(this.original);
return isFloat(this.original) ? floatToBinary(this.original, { precision }) : integerToBinary(this.original);
}
toInteger({ isSigned = false } = {}) {
if (!isSigned) //@ts-ignore
return parseInt(this.original);
const hex = this.original.toString(16);
return hexStringToInteger(hex, { isSigned });
}
/**
* Does not support bigint(above 32 bit) or floating point.
*/
toBytes({ endianness = 'BIG' } = {}) {
return getBytesFromInteger(this.original, { endianness });
}
toDecimalBytes({ endianness = 'BIG', isSigned = false } = {}) {
return getDecimalBytesFromInteger(this.original, { endianness, isSigned });
}
toHexString({ precision = 'SINGLE' } = {}) {
if (typeof this.original === 'number') {
if (isFloat(this.original)) {
return floatToHexString(this.original, { precision });
}
return integerToHexaDecimal(this.original);
}
return bigIntegerToHexaDecimal(this.original);
}
toFloat({ precision = 'SINGLE' } = {}) {
const float = hexStringToFloat(this.original.toString(16), { precision });
return float;
}
}
//# sourceMappingURL=NumberConverter.js.map