Domanda

Nei framework applicativi continuo a vedere framework che consentono di passare a più valori Int (generalmente utilizzati al posto di un enum) in una funzione.

Ad esempio:

public class Example
{ 
    public class Values
    {
        public static final int ONE = 0x7f020000;
        public static final int TWO = 0x7f020001;
        public static final int THREE = 0x7f020002;
        public static final int FOUR = 0x7f020003;
        public static final int FIVE = 0x7f020004;
    }

    public static void main(String [] args)
    {
        // should evaluate just Values.ONE
        Example.multiValueExample(Values.ONE);

        // should evalueate just values Values.ONE,  Values.THREE, Values.FIVE
        Example.multiValueExample(Values.ONE | Values.THREE | Values.FIVE);

        // should evalueate just values Values.TWO , Values.FIVE
        Example.multiValueExample(Values.TWO | Values.FIVE);
    }

    public static void multiValueExample(int values){
        // Logic that properly evaluates bitwise values
        ...
    }
}

Quindi quale logica dovrebbe esistere in multiValueExample per poter valutare correttamente più valori int che vengono passati usando l'operatore bitwise?

È stato utile?

Soluzione

I tuoi valori dovrebbero essere poteri di 2.

In questo modo, non perdi alcuna informazione quando le OR o bit per bit.

public static final int ONE   = 0x01;
public static final int TWO   = 0x02;
public static final int THREE = 0x04;
public static final int FOUR  = 0x08;
public static final int FIVE  = 0x10;

ecc.

Quindi puoi farlo:

public static void main(String [] args) {
    Example.multiValueExample(Values.ONE | Values.THREE | Values.FIVE);
}

public static void multiValueExample(int values){
    if ((values & Values.ONE) == Values.ONE) {
    }

    if ((values & Values.TWO) == Values.TWO) {
    }

    // etc.
}

Altri suggerimenti

Come già accennato, considera l'uso di enum invece di valori di bit.

Secondo Java 2 effettivo : " Articolo 32: Usa EnumSet invece di campi bit "

L'utilizzo di EnumSet è abbastanza efficace per l'utilizzo della memoria e molto conveniente.

Ecco un esempio:

package enums;

import java.util.EnumSet;
import java.util.Set;

public class Example {
  public enum Values {
    ONE, TWO, THREE, FOUR, FIVE
  }

  public static void main(String[] args) {
    // should evaluate just Values.ONE
    Example.multiValueExample(EnumSet.of(Values.ONE));

    // should evalueate just values Values.ONE, Values.THREE, Values.FIVE
    Example.multiValueExample(EnumSet.of(Values.ONE, Values.THREE, Values.FIVE));

    // should evalueate just values Values.TWO , Values.FIVE
    Example.multiValueExample(EnumSet.of(Values.TWO, Values.FIVE));
  }

  public static void multiValueExample(Set<Values> values) {
    if (values.contains(Values.ONE)) {
      System.out.println("One");
    }

    // Other checks here...

    if (values.contains(Values.FIVE)) {
      System.out.println("Five");
    }
  }
}

I valori interi vengono impostati come potenze di due in modo che ciascun valore elencato sia un singolo bit nella rappresentazione binaria.

int ONE = 0x1;    //0001
int TWO = 0x2;    //0010
int THREE = 0x4;  //0100
int FOUR = 0x8;   //1000

Quindi usi OR per bit per combinare valori e AND bit per bit per testare i valori impostati.

int test_value = (ONE | FOUR);   //-> 1001
bool has_one = (test_value & ONE) != 0;  //-> 1001 & 0001 -> 0001 -> true

I valori che combini con | (OR binario, non OR logico [che è ||]) non devono avere "1" sovrapposti nella loro rappresentazione bit. Ad esempio,

ONE = 0x1 =   0000 0001
TWO = 0x2 =   0000 0010
THREE = 0x3 = 0000 0011
FOUR = 0x4 =  0000 0100

Quindi puoi combinare UNO e DUE, ad esempio:

ONE | TWO = 0000 0011

Ma non puoi distinguere ONE | DUE DA TRE, perché ci sono punte sovrapposte. I numeri che combini dovrebbero quindi essere poteri di due, in modo tale che non si sovrappongano quando vengono uniti insieme. Per verificare se un numero è stato passato in "quotazioni", fai:

if (values & ONE) {
    // ... then ONE was set
}

Per capire meglio perché e come funziona, ti consiglio di leggere un po 'la rappresentazione e la logica binarie. Un buon posto è Capitolo 3 dell'Arte dell'Assemblea .

Bene, se sono potenze di 2, faresti qualcosa come il "display" " metodo nel codice seguente.

Ecco un link in wikipedia anche sull'argomento che dovrebbe spiega perché vuoi poteri di 2.

public class Main
{
    private static final int A = 0x01;
    private static final int B = 0x02;
    private static final int C = 0x04;

    public static void main(final String[] argv)
    {
        display(A);
        display(B);
        display(C);
        display(A | A);
        display(A | B);
        display(A | C);
        display(B | A);
        display(B | B);
        display(B | C);
        display(C | A);
        display(C | B);
        display(C | C);
        display(A | A | A);
        display(A | A | B);
        display(A | A | C);
        display(A | B | A);
        display(A | B | B);
        display(A | B | C);
        display(A | C | A);
        display(A | C | B);
        display(A | C | C);
        display(B | A | A);
        display(B | A | B);
        display(B | A | C);
        display(B | B | A);
        display(B | B | B);
        display(B | B | C);
        display(B | C | A);
        display(B | C | B);
        display(B | C | C);
        display(C | A | A);
        display(C | A | B);
        display(C | A | C);
        display(C | B | A);
        display(C | B | B);
        display(C | B | C);
        display(C | C | A);
        display(C | C | B);
        display(C | C | C);
    }

    private static void display(final int val)
    {
        if((val & A) != 0)
        {
            System.out.print("A");
        }

        if((val & B) != 0)
        {
            System.out.print("B");
        }

        if((val & C) != 0)
        {
            System.out.print("C");
        }

        System.out.println();
    }
}

L'uso delle maschere di bit era popolare quando si contava ogni bit. Un altro modo per farlo oggi è usare gli enum con che sono più semplici da manipolare ed estendere.

import static Example.Values.*;
import java.util.Arrays;

public class Example {
    public enum Values { ONE, TWO, THREE, FOUR, FIVE }

    public static void main(String [] args) {
        // should evaluate just Values.ONE
        multiValueExample(ONE);

        // should evaluate just values Values.ONE,  Values.THREE, Values.FIVE
        multiValueExample(ONE, THREE, FIVE);

        // should evaluate just values Values.TWO , Values.FIVE
        multiValueExample(TWO, FIVE);
    }

    public static void multiValueExample(Values... values){
        // Logic that properly evaluates
        System.out.println(Arrays.asList(values));
        for (Values value : values) {
            // do something.
        }
    }
}

Innanzitutto, non è possibile definire i valori in questo modo per eseguire confronti bit a bit. Invece, imposta bit diversi:

public static final int ONE   = 0x1;  // First bit is set
public static final int TWO   = 0x2;  // Second bit is set
public static final int THREE = 0x4;  // Third bit is set
public static final int FOUR  = 0x8;  // Fourth bit is set
public static final int FIVE  = 0x10; // Fifth bit is set

Secondo, dovresti probabilmente usare java.util.BitSet per questo tipo di operazioni:

BitSet bits = new BitSet(5);
bits.set(2);
bits.set(4);

System.out.println("these bits are set: " + bits);
// Prints "these bits are set: {2, 4}"

BitSet otherBits = new BitSet(5);
otherBits.set(3);
otherBits.set(4);

System.out.println("these bits are set: " + bits.or(otherBits));
// Prints "these bits are set: {2, 3, 4}"

Il capitolo Tutorial Java sulle operazioni bit a bit si trova su

http://java.sun.com/docs /books/tutorial/java/nutsandbolts/op3.html

È molto conciso ma buono come riferimento.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top