Berstos
Berstos

Reputation: 179

Check if flags are set in big integer

I have two flags "32" and "64" which need to be checked if they're included inside an integer variable.

Therefore I'm using the following code which is working fine with "small integers". For example if the integer variable is "33555378" it outputs the right results.

Now I have the problem that the integer variable is "12261800583900083122" and the script doesn't seem to work correctly.

How do I check if flags are set in big integers correctly?

This is the JSFiddle.

Code:

var flags = {
    Horde: 32, 
    Allianz: 64,
}

var flag = 12261800583900083122;

if ((flag & flags.Horde) == flags.Horde && (flag & flags.Allianz) == flags.Allianz) {
     console.log('Both');
} else if ((flag & flags.Allianz) == flags.Allianz) {
     console.log('Allianz');
} else if ((flag & flags.Horde) == flags.Horde) {
     console.log('Horde');
} else {
     console.log('Nothing');
}

Upvotes: 1

Views: 169

Answers (1)

Sercan
Sercan

Reputation: 2169

I think using BigInt (adding n after numbers) for both flags and flag can fix your problem;

var flags = {
    Horde: 32n, 
    Allianz: 64n,
}

var flag = 12261800583900083122n;

if ((flag & flags.Horde) == flags.Horde && (flag & flags.Allianz) == flags.Allianz) {
     console.log('Both');
} else if ((flag & flags.Allianz) == flags.Allianz) {
     console.log('Allianz');
} else if ((flag & flags.Horde) == flags.Horde) {    
     console.log('Horde');
} else {
     console.log('Nothing');
}

This results as Horde.

Upvotes: 1

Related Questions