Fagner Brack
Fagner Brack

Reputation: 2403

Ignoring the first bit using bitwise compare with permission model

I have the bits 101 and 110. I want to compare using some bitwise operator ignoring the first bit like 01 and 10.

Example:

I have:
101
110
===
01 & 10 <- How I want to consider
x00 <- The result I want

or

10110
11011
=====
0110 & 1011 <- How I want to consider
x0010 <- The result I want

How could I achieve this using bitwise operators in java?

Details:

Use case:

Any better solution for this case will be considered a correct answer also.

Upvotes: 2

Views: 722

Answers (3)

gaborsch
gaborsch

Reputation: 15758

If you know the number of useful bits (e.g numofbits = 5) then the bitmask for the expression is:

bitmask = (1 << numofbits) - 1

If you don't know the numofbits, just make a loop with num = num >> 1, and count the iteration until you got num == 0.

For the use case:

result = (req_roles & user_roles) & (bitmask >> 1)

This simply ands the role bits, ans cuts the upper bit (which is always 1)


Previous answer for previous question :) :

If you know the bitmask for the highest number (e.g. bitmask = 0x1f (11111 in bits)) then you want the result of the following expression:

result = (a ^ b) ^ (bitmask >> 1)

What does it do?

  • Compares all bits, the equal bits will be 0
  • Reverts all lower bits, so equal bits will be 1 (leaves the high bit out, so it will remain 0)

Upvotes: 3

Peter Wooster
Peter Wooster

Reputation: 6089

Just 'and' the arguments with a mask that has the first bit off, eg 011 & arg before you compare them.

Edit: after restated question.

The alternative is to use role based permissions, these are far more flexible and easier to understand than Boolean permission strings. They are also self documenting. Bit string based permissions are rarely used except where memory or disk space are at a premium, like when Unix was developed back in the early '80s or in embedded systems.

Upvotes: 3

Java42
Java42

Reputation: 7706

Try this:

// tester 1
int x, y, z, mask;
x = 0x05; // 101
y = 0x06; // 110
mask = getMask(x, y);
z = (mask & (x & y));
System.out.println(String.format("mask: %x result: %x", mask, z));

// tester 2    
int x, y, z, mask;
x = 0x16; // 10110
y = 0x1B; // 11011
mask = getMask(x, y);
z = (mask & (x & y));
System.out.println(String.format("mask: %x result: %x", mask, z));

private int getMask(final int x, final int y) {
    int mask = findHighOrderOnBit(x, 0);
    mask = findHighOrderOnBit(y, mask) - 1;
    return mask;
}

private int findHighOrderOnBit(final int target, final int otherMask) {
    int result = 0x8000;
    for (int x = 0; x != 16; x++) {
        if ((result & target) > 0)
            break;
        result >>= 1;
    }
    if (otherMask > result)
        result = otherMask;
    return result;
}

Upvotes: 1

Related Questions