Originally Posted by
Perd1t1on
what do you mean by a four bit primitive?
I was simply restating what I thought you meant
Here's is an example of what I was alluding to:
public static void main(String[] args){
byte one = 1;
byte ten = 10;
byte combined = (byte)((one << 4 ) | ten);
System.out.println("One = " + one);
System.out.println("Ten = " + ten);
System.out.println("Combined = " + combined);
byte one2 = (byte)(combined >> 4);
byte ten2 = (byte)(combined & 0x0f);
System.out.println("One = " + one2);
System.out.println("Ten = " + ten2);
}
This example packs two numbers into a single byte, then extracts them back out using bit shifting. This can be used for all sorts of things. One common problem is how to store and transfer a variable number of options (aka flags). Passing them as bitwise values rather than booleans is a great way to do so. Each byte being a zero and a one, and each 'on' byte a power of two, you can set an integer's bits by 'anding' the integer with that value, as follows:
static int PRINT_YES = 1;
static int PRINT_NO = 2;
static int PRINT_HELLO = 4;
static int PRINT_WORLD = 8;
private static void printer(int vals){
if ( (vals & PRINT_NO) != 0 ){
System.out.println("NO");
}
if ( (vals & PRINT_YES) != 0 ){
System.out.println("YES");
}
if ( (vals & PRINT_HELLO) != 0 ){
System.out.println("HELLO");
}
if ( (vals & PRINT_WORLD) != 0 ){
System.out.println("WORLD");
}
}
public static void main(String[] args){
printer(PRINT_HELLO | PRINT_WORLD );
}
Not sure if this fully addresses your original question, but this does allow you to use primitives to technically store variable bit sized values.