binary_to_symbolic.js (2570B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 var toBinaryString = require( '@stdlib/number/uint16/base/to-binary-string' ); 22 var lpad = require( '@stdlib/string/left-pad' ); 23 24 // Set this to "pretty" print results: 25 var PRETTY_PRINT = false; 26 27 var TOTAL; 28 var masks; 29 var bstr; 30 var perm; 31 var who; 32 var tmp; 33 var i; 34 var j; 35 36 // Total number of combinations (octal numbers): 37 TOTAL = 8 * 8 * 8 * 8; 38 39 // For each integer value (octal number), determine the symbolic notation equivalent to the value's binary representation... 40 masks = new Array( TOTAL ); 41 for ( i = 0; i < TOTAL; i++ ) { 42 tmp = ''; 43 44 // Convert the octal value to its binary representation: 45 bstr = toBinaryString( i ); 46 47 // Discard the first four bits (a four digit octal number only uses 12 bits): 48 bstr = bstr.substring( 4 ); 49 50 // Iterate over each bit starting from the fourth bit (left-to-right; the leftmost three bits are special mode bits, which are ignored when the mask is applied) and determine whether a bit is clear. If the bit is clear, the mask allows a permission to be enabled. 51 for ( j = 3; j < bstr.length; j++ ) { 52 who = (j-3) / 3; 53 if ( who === (who|0) ) { // is integer check 54 // Determine the user class: 55 who |= 0; 56 if ( who === 0 ) { 57 who = 'u'; 58 } else if ( who === 1 ) { 59 who = 'g'; 60 } else { 61 who = 'o'; 62 } 63 if ( j >= 6 ) { // who|0 > 0 64 tmp += ','; 65 } 66 tmp += who + '='; 67 } 68 if ( bstr[ j ] === '0' ) { 69 // Determine the permission: 70 perm = j % 3; 71 if ( perm === 0 ) { 72 perm = 'r'; 73 } else if ( perm === 1 ) { 74 perm = 'w'; 75 } else { 76 perm = 'x'; 77 } 78 tmp += perm; 79 } 80 } 81 // [ integer, octal, binary_string, symbolic_notation ] 82 masks[ i ] = [ i, lpad( i.toString( 8 ), 4, '0' ), bstr, tmp ]; 83 } 84 85 if ( PRETTY_PRINT ) { 86 // Print the list of masks in symbolic notation: 87 for ( i = 0; i < TOTAL; i++ ) { 88 console.log( '%d = %s = %s = %s', masks[i][0], masks[i][1], masks[i][2], masks[i][3] ); 89 } 90 } else { 91 console.log( JSON.stringify( masks ) ); 92 }