Skip to content

Instantly share code, notes, and snippets.

@tj-commits
Created March 1, 2025 17:30
Show Gist options
  • Save tj-commits/8eec826d602fb191922634312ae656ad to your computer and use it in GitHub Desktop.
Save tj-commits/8eec826d602fb191922634312ae656ad to your computer and use it in GitHub Desktop.
JavaScript function to convert from binary to decimal
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