I'm trying to create a Java class that will hold some settings flags. Class members:
- HEADER
- FOOTER
- LEFT_SECTION
- RIGHT_SECTION
These can be enabled/disabled. I want to do it with bit wise operations but I was wondering if it's possible because I will not set all of them at a given time. I just want to set one and leave the others the same.
Give a current state 0100, so only the FOOTER is enabled, is it possible to enable the HEADER and preserve the FOOTER flag value?
If my scenario is possible?
Main Class
package foo;
public class Main {
private static final SectionVisible sectionVisible = new SectionVisible();
public static void main(String[] args) {
// Enable FOOTER only
sectionVisible.setValue(2); // 00000010
printState();
// Enable LEFT_SECTION but preserve FOOTER's value
sectionVisible.setValue(4); // 00000100
printState();
}
private static void printState() {
System.out.println("header=" + sectionVisible.header());
System.out.println("footer=" + sectionVisible.footer());
System.out.println("leftSection=" + sectionVisible.leftSection());
System.out.println("----------------------------------------------------");
}
}
SectionVisible Class
package foo;
class SectionVisible {
private static final Integer LEFT_SECTION_MASK = 4;
private static final Integer LEFT_SECTION_OFFSET = 2;
private static final Integer FOOTER_MASK = 2;
private static final Integer FOOTER_OFFSET = 1;
private static final Integer HEADER_MASK = 1;
private static final Integer HEADER_OFFSET = 0;
private Integer value;
public Integer header() {
return (value & HEADER_MASK) >> HEADER_OFFSET;
}
public Integer footer() {
return (value & FOOTER_MASK) >> FOOTER_OFFSET;
}
public Integer leftSection() {
return (value & LEFT_SECTION_MASK) >> LEFT_SECTION_OFFSET;
}
public void setValue(Integer value) {
System.out.println(
"Setting value to " + value + ":" + Integer.toBinaryString(value));
this.value = value;
}
}
Execution Log
Setting value to 2:10
header=0
footer=1
leftSection=0
----------------------------------------------------
Setting value to 4:100
header=0
footer=0
leftSection=1
----------------------------------------------------
The problem is that when I'm setting the LEFT_SECTION's value, I'm losing the FOOTER's value.