Forum Moderators: open

Message Too Old, No Replies

Is a number "in" another number?

Additive codes based on linux file/directory permissions

         

ocon

9:58 pm on Jun 20, 2015 (gmt 0)

10+ Year Member Top Contributors Of The Month



I'm trying to determine if a product code is allowed to be transported by a set transportation mode. The transportation codes are based on the following table:

Car = 1
Truck = 2
Train = 4

I might be given the code of 1 which means the item can be transported by Car, 3 means it can go by Car or Truck (1+2=3), or 7 means it can go by Car, Truck or Train (1+2+4=7), and so forth.

How can I make this work?

var transmode = 5;
if(productcode "in" transmode){do something;}

Fotiman

2:53 am on Jun 21, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



This is a bitmask.
Consider these numbers when they are converted to binary (note, I'm using 8 bits for these... because showing all 32 bits is not useful for this demonstration):
1 = 00000001
2 = 00000010
3 = 00000011
4 = 00000100
5 = 00000101
6 = 00000110
7 = 00000111

So can do bitwise & (AND) operations to determine if one of these flags is set. For example:

var Car = 1,
Truck = 2,
Train = 4;

var transmode = 5; // 00000101, aka: Car + Train
if (Car & transmode) {
// do something
}


More info on Bitwise operators available:
[developer.mozilla.org...]

lucy24

4:27 am on Jun 21, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



... and if you have trouble internalizing 2 4 8 16 32 etcetera,* you can call the successive modes 1 2 3 etcetera and express it as Math.pow(2,whatever-the-syntax-is) ;)



* My brain gives out around 4096.

ocon

11:18 am on Jun 21, 2015 (gmt 0)

10+ Year Member Top Contributors Of The Month



That's awesome, thank you. I knew it was based on the binary position but I had no idea of the bitwise operator, in fact I had to reread that multiple times because always converted it to && (logical and). This saves me from an if/else hell, thanks.