Skip to content

Instantly share code, notes, and snippets.

Last active Dec 10, 2015
What would you like to do?
BIN2OCT Function
// Copyright (c) 2012 Sutoiku, Inc. (MIT License)
function BIN2OCT(number, places) {
// Return error if number is not binary or contains more than 10 characters (10 digits)
if (!/^[01]{1,10}$/.test(number)) return '#NUM!';
// Ignore places and return a 10-character octal number if number is negative
var stringified = number.toString();
if (stringified.length === 10 && stringified.substring(0, 1) === '1') {
return (1073741312 + parseInt(stringified.substring(1), 2)).toString(8);
// Convert binary number to octal
var result = parseInt(number, 2).toString(8);
// Return octal 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!';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment