In some places, you’ll see options saved as numbers. For example, when setting file permissions, you pass them using a value ranging from 0 to 7 for each group of users.
Each one of the bits in the binary representation of the number represents one of three permissions: read, write and execute, so a value of 7, with a binary representation of 111 means that the file can be read, written and executed, whereas a value of 5 means that the file can only be read and executed because of the binary representation 101.
side note: I’m not an expert on how operating systems manage files; my explanation may be wrong, but I’m sure that the basic idea of binary numbers representing these options is implemented there.
I am now wondering if it is efficient to store true/false options in binary using JavaScript. To do so, I would create the JavaScript as follows:
function OptionsGenerator(){
//this method takes a number, and returns an array of options.
this.num2options = function(num){
var str,len,opts=[];
if(typeof num !== "number") return false;
str = num.toString(2);
len = str.length;
for(var i=0;i<len;i++){
opts[i] = (str.charAt(i)==="1") ? true : false;
}
return opts;
}
//this function gets an array of options, and returns a number.
this.options2num = function(opts){
var str = "",o,opt;
for(o in options){
opt = (options[o]) ? 1 : 0;
str+=opt;
}
return parseInt(str,2);
}
//this function returns a specific option with an index ranging from 1 to the number of options set. takes 2 arguments: the first one is the set of options. This can either be a number or a string containing a binary representation of the number, the second parameter contains the index of the option.
this.getOption = function(num,optnum){
var str;
if(typeof num === 'number')
str = num.toString(2);
else
str = num;
return (num.charAt(optnum-1)==="1");
}
}
My question is: is this an efficient way to save options, and if it is, is there a more efficient way to convert from binary to a number, and to get a specific option, or all the options?
If you are wanting to accomplish something similar in JavaScript, I would recommend actually using bitwise operators, namely & and |.
For example: