简体   繁体   English

JavaScript位掩码

[英]Javascript bit masks

I've used bit masks in Java (not Javascript) before, but it's been a while and it's making me bug out. 我以前在Java(不是Javascript)中使用过位掩码,但是已经有一段时间了,这让我很烦。

This is the Typescript I'm wanting to work with. 这是我要使用的打字稿。 Theres 3 roles, 有3个角色,

enum Type {
    FRUIT = 0x1,
    VEGGIE = 0x2,
    BOTH = FRUIT | VEGGIE
}

class Thing {
    role:number;

    constructor(role:Type){
        this.role = role;
    }
    getRole(){
        return this.role;
    }
    is(role:Type) {
        return !!(this.role & role);
    }
}

var whatever = new Thing(Type.FRUIT);

console.log('fruit', whatever.is(Type.FRUIT));
console.log('veggie', whatever.is(Type.VEGGIE));
console.log('both', whatever.is(Type.BOTH));

// fruit true
// veggie false
// both true

I conceptually see why "both" is coming back as "true", but my bit math isn't great. 我从概念上了解了为什么“两个”又返回“真实”,但是我的数学并不好。

When the role is either FRUIT or VEGGIE , the others are false. 当角色为FRUITVEGGIE ,其他角色为false。 When it's set to BOTH , all should be true. 设置为BOTH ,都应该为true。

Tried a few combinations of shifts and bit operations, but I can't get that output. 尝试了一些移位和位运算的组合,但我无法获得该输出。 If I try them separate it's fine, but I'd like to use combinations of bits to build. 如果我尝试将它们分开,那很好,但是我想使用位组合来构建。

When you perform a bitwise & operation the result is that the bits turned on in both values used in the expression. 当执行按位&运算时,结果是表达式中使用的两个值中的位均打开。

For example (taken from Pro TypeScript , p 207) 例如(摘自Pro TypeScript ,第207页)

a 1011
&
b 1101
= 1001

The first column, both values are "switched on (1)", so the result is also switched on. 在第一列中,两个值都“已打开(1)”,因此结果也已打开。 The second column, a is switched off, so the result is 0 , the third column b is off, so again a 0 and finally the last column both are on, so a 1 . 第二列a被关闭,因此结果为0 ,第三列b被关闭,因此a再次为0 ,最后最后一列都为on,因此a 1

In your case, it is even simpler because you are dealing with such small numbers... 就您而言,它甚至更简单,因为您处理的是这么小的数字...

a 01 // FRUIT
&
b 11 // ALL
= 01 // FRUIT

So the result is 01 , or 1 if you have ten fingers. 因此,结果为01 ,如果您有十根手指,则为1

If you use a double-bang !! 如果您使用双响!! to convert 1 to to a boolean (I call this slacker parsing ), you'll get true because 1 is truth-y. 1转换为布尔值(我称之为slacker parsing ),您将得到true因为1true -y。 This doesn't answer the question you were really asking, which is "does this bit flag match". 这不能回答您真正提出的问题,即“该位标志是否匹配”。

This is why this.role & role === role is the correct code, because you won't get a mistake from the "truthiness" of the value 1 . 这就是为什么this.role & role === role是正确的代码的原因,因为您不会从值1的“真实性”中得到一个错误。

 return !!(this.role & role); 

您的版本可以按isAny ,但是您希望它按isAll

return (this.role & role) === role;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM