Last active
December 10, 2015 19:18
-
-
Save ghalimi/4480223 to your computer and use it in GitHub Desktop.
BIN2DEC Function
This file contains 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
// Copyright (c) 2012 Sutoiku, Inc. (MIT License) | |
function BIN2DEC(number) { | |
// Return error if number is not binary or contains more than 10 characters (10 digits) | |
if (!/^[01]{1,10}$/.test(number)) return '#NUM!'; | |
// Convert binary number to decimal | |
var result = parseInt(number, 2); | |
// Handle negative numbers | |
var stringified = number.toString(); | |
if (stringified.length === 10 && stringified.substring(0, 1) === '1') { | |
return parseInt(stringified.substring(1), 2) - 512; | |
} else { | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment