Convert a binary number to octal | Function to create map between binary number and its equivalent hexadecimal ; Function to find octal equivalent of binary ; Length of string before ' . ' ; Add min 0 's in the beginning to make  left substring length divisible by 3 ; If decimal point exists ; Length of string after ' . ' ; add min 0 's in the end to make right  substring length divisible by 3 ; Create map between binary and its equivalent octal code ; One by one extract from left , substring of size 3 and add its octal code ; If ' . ' is encountered add it to result ; Required octal number ; Driver code
function createMap ( um ) { um . set ( " " , ' ' ) ; um . set ( " " , ' ' ) ; um . set ( " " , ' ' ) ; um . set ( " " , ' ' ) ; um . set ( " " , ' ' ) ; um . set ( " " , ' ' ) ; um . set ( " " , ' ' ) ; um . set ( " " , ' ' ) ; } function convertBinToOct ( bin ) { let l = bin . length ; let t = bin . indexOf ( ' ' ) ; let len_left = t != - 1 ? t : l ; for ( let i = 1 ; i <= ( 3 - len_left % 3 ) % 3 ; i ++ ) bin = ' ' + bin ; if ( t != - 1 ) { let len_right = l - len_left - 1 ; for ( let i = 1 ; i <= ( 3 - len_right % 3 ) % 3 ; i ++ ) bin = bin + ' ' ; } let bin_oct_map = new Map ( ) ; createMap ( bin_oct_map ) ; let i = 0 ; let octal = " " ; while ( true ) { octal += bin_oct_map . get ( bin . substr ( i , 3 ) ) ; i += 3 ; if ( i == bin . length ) break ; if ( bin . charAt ( i ) == ' ' ) { octal += ' ' ; i ++ ; } } return octal ; } let bin = " " ; document . write ( " " + convertBinToOct ( bin ) ) ;