Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
HEX2BIN Function
// Copyright (c) 2012 Sutoiku, Inc. (MIT License)
function HEX2BIN(number, places) {
// Return error if number is not hexadecimal or contains more than ten characters (10 digits)
if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) return '#NUM!';
// Check if number is negative
var negative = (number.length === 10 && number.substring(0, 1).toLowerCase() === 'f') ? true : false;
// Convert hexadecimal number to decimal
var decimal = (negative) ? parseInt(number, 16) - 1099511627776 : parseInt(number, 16);
// Return error if number is lower than -512 or greater than 511
if (decimal < -512 || decimal > 511) return '#NUM!';
// Ignore places and return a 10-character binary number if number is negative
if (negative) return '1' + _s.repeat('0', 9 - (512 + decimal).toString(2).length) + (512 + decimal).toString(2);
// Convert decimal number to binary
var result = decimal.toString(2);
// Return binary number using the minimum number of characters necessary if places is undefined
if (typeof places === 'undefined') {
return result;
} else {
// Return error if places is nonnumeric
if (isNaN(places)) return '#VALUE!';
// Return error if places is negative
if (places < 0) return '#NUM!';
// Truncate places in case it is not an integer
places = Math.floor(places);
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string)
return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!';
}
}
@camsjams

This comment has been minimized.

Copy link

@camsjams camsjams commented Aug 7, 2016

You can change
var negative = (number.length === 10 && number.substring(0, 1).toLowerCase() === 'f') ? true : false;
to:
var negative = !!(number.length === 10 && number.substring(0, 1).toLowerCase() === 'f');

On LN#8 for a little brevity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment