最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

math - Using javascript to decode bit values - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Apr 29, 2011 at 22:36 sterlingsterling 6252 gold badges12 silver badges23 bronze badges 2
  • If you passed in 127, what would you expect to be returned? – hookedonwinter Commented Apr 29, 2011 at 22:37
  • Sounds like dec-to-bin conversion... – Šime Vidas Commented Apr 29, 2011 at 22:37
Add a ment  | 

2 Answers 2

Reset to default 7

Sounds like a bitmask. You can read about bitmasks here; http://en.wikipedia/wiki/Mask_%28puting%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
function dec2bin(n) {
    return n.toString(2).split('');
}

And then:

dec2bin(127) // returns ['1', '1', '1', '1', '1', '1', '1']

dec2bin(38) // returns ['1', '0', '0', '1', '1', '0']
发布评论

评论列表(0)

  1. 暂无评论