Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using javascript to decode bit values

Given the following scale:

Mon = 64, Tue = 32, Wed = 16, Thu = 8, Fri = 4, Sat = 2, Sun = 1

How would you create a function that is passed an integer to decode the corresponding days of the week?

For example, say the value 127 was passed, how can you determine what days are included in that value?

like image 839
sterling Avatar asked Oct 30 '25 21:10

sterling


1 Answers

Sounds like a bitmask. You can read about bitmasks here; http://en.wikipedia.org/wiki/Mask_%28computing%29

Sunday would be the 1st bit, Sat the 2nd, etc, Mon the 7th. To see if a day is included, use a binary AND.

var listOfDays = 127;
var hasSun = listOfDays & 1; 
var hasSat = listOfDays & 2;
var hasFri = listOfDays & 4;
// etc
like image 53
xconspirisist Avatar answered Nov 02 '25 12:11

xconspirisist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!