Can I use bytes for a boolean array?

In the application we are creating (iOS / Swift, Android), we have a settings page when the user wants to receive push notifications. One of the parameters is the selection by the user of the days of the week.

My question is how to save this parameter as one variable, not seven booleans. This parameter will be sent to the server / database to be saved, and I thought we could just use a single byte field in the database. Instead monday=true, tuesday=false, ..., I would like to use, for example, "10001010", where 1 is true and 0 is false, which will translate to monday=true(1), tuesday=false(0), etc(this Monday is the first day of the week that it ...).

Is this a valid way to store such data? Can I create such a byte? Or is it a more practical practice using the / char [] string "10001010"? Or can databases (e.g. MySQL) store bool [] (10001010) as a single field? Or is there another, best practice for this? The method used for permissions also came to mind (you know, just 777)

Of course, some options will require the server to use the same logic for the variable, but in this case there is no problem.

A brief explanation. I need seven boolean elements, one for each day of the week, and I want to store it more efficiently than one variable per day. Is there a "best practice"?

+4
source share
4 answers

"" :

  • , 7 , (, 7 x 4 )... .

  • ... .

  • ... .


?

"". , ( ).

,

... ? , () .


, //. :

+4

.

class A {
    public static final int MONDAY = 0;
    ...
    public static final int SUNDAY = 6;

    // call with the above defined constants for day
    public byte addDay(byte b, int day) {
        return (byte) (b | (1 << day));
    }

    public boolean isDaySet(byte b, int day) {
        return ((b >> day) & 1) == 1 ;
    }
}

, , , , .

+1

.

enum Days {
    MON,
    TUE,
    WED,
    THU,
    FRI,
    SAT,
    SUN
}

public static void main(String[] args) {

    byte encode = (byte)0b1010000;

    for ( Days d : Days.values() ) {
        boolean present = (encode & 1<<d.ordinal()) != 0;
        System.out.println(d + " " + present);
    }

    System.out.println("Adding MON, removing SUN");

    encode |= (1<<Days.MON.ordinal());
    encode &= ~(1<<Days.SUN.ordinal());

    for ( Days d : Days.values() ) {
        boolean present = (encode & 1<<d.ordinal()) != 0;
        System.out.println(d + " " + present);
    }

}

, / , , enum 1 <

+1
source

Consider using EnumSet as described in paragraph 32 of Joshua Bloch's Effective Java. (EnumSets are internally BitVectors)

Use java.time.DayOfWeekas an enumeration type.

The days of the week contained in the set are user selected. The rest are not selected.

EnumSet<DayOfWeek> selectedDays = EnumSet.of(DayOfWeek.MONDAY, DayOfWeek.FRIDAY);

selectedDays.contains(DayOfWeek.MONDAY); // true
selectedDays.contains(DayOfWeek.TUESDAY); // false
0
source

All Articles