Created
March 1, 2025 17:30
-
-
Save tj-commits/8eec826d602fb191922634312ae656ad to your computer and use it in GitHub Desktop.
JavaScript function to convert from binary to decimal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const IS_BINARY_REGEX = /^[01]+$/ | |
const reverseString = require('reverse-string') | |
const { immediateError, ErrorType } = require('immediate-error') | |
function binary2decimal(binary) { | |
if (typeof binary !== 'string' && !(binary instanceof String) && typeof binary !== 'number' && !(binary instanceof Number)) { | |
return immediateError('Binary must be a string or fake decimal number that consists of ones and zeroes and is actually a binary number.', ErrorType.TypeError) | |
} | |
binary = binary.toString() | |
if (!binary.match(IS_BINARY_REGEX)) { | |
return immediateError('Binary must be actual binary and only consist of ones and zeroes.', ErrorType.TypeError) | |
} | |
let decimal = 0 | |
let currentPlace = 1 | |
const binaryReversed = reverseString(binary) | |
const binaryArray = binaryReversed.split('') | |
binaryArray.forEach(bit => { | |
decimal += currentPlace * parseInt(bit) | |
currentPlace = currentPlace * 2 | |
}) | |
return decimal | |
} | |
module.exports = binary2decimal |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment