Re: Merging bytes
On Mon, 26 Apr 2010 12:39:06 -0700 (PDT), mikew01
<mikew01@blueyonder.co.uk> wrote:
On Apr 26, 6:06??pm, rossum <rossu...@coldmail.com> wrote:
On Mon, 26 Apr 2010 03:59:25 -0700 (PDT), mikew01
<mike...@blueyonder.co.uk> wrote:
Hello
I need to combine 3 number values into a 2 byte array.
The value bit sizes are:
value1 = 6 bits.
value2 = 6 bits.
value3 = 12 bits.
I understand I need to use the bit manipulation operators to do this
but would like some advice on the best approach using Java.
Thanks
Mike.
As Jan has pointed out you cannot fit 24 bits into 16 bits. ??You need
to rethink the specification. ??Why are you trying to compress data
like this? ??What other ways are there to compress the data?
Trying to do a lot of bit-twiddling will slow down your application.
rossum
Sorry there is a typo in the first post, value3 is 4 bits not 12
It's not up to me how the data is packaged unfortunately, I am dealing
with a platform that has very limited resources so every bit counts.
Thanks
Mike
OK, so that is:
value1 = 6 bits.
value2 = 6 bits.
value3 = 4 bits.
16 bits is a short, so you are probably better off using a short than
an array of bytes, there is less overhead than with an array.
A class may be more than you can afford in memory terms, but here is
my first cut. The bit-shifting should be useful anyway. Warning,
completely untested.
final class BitTwiddler {
private final static int SIX_BIT_MASK = 0x3F;
private final static int FOUR_BIT_MASK = 0xF;
private final static int VAL_2_POSN = 6;
private final static int VAL_3_POSN = 12;
// Holds the three values in 16 bits.
// 3333222222111111
private short mData = 0;
public BitTwiddler() { }
public void setValue1(int val1) {
// Clear old v1 bits
mData ^= getValue1();
// Add in new v1 bits
mData += (val1 & SIX_BIT_MASK);
}
public int getValue1() {
return mData & SIX_BIT_MASK;
}
public void setValue2(int val2) {
// Clear old v2 bits
mData ^= (getValue2() << VAL_2_POSN);
// Add in new v2 bits
mData += ((val2 & SIX_BIT_MASK) << VAL_2_POSN);
}
public int getValue2() {
return (mData >>> VAL_2_POSN) & SIX_BIT_MASK;
}
public void setValue3(int val3) {
// Clear old v3 bits
mData ^= (getValue3() << VAL_3_POSN);
// Add in new v3 bits
mData += ((val3 & FOUR_BIT_MASK) << VAL_3_POSN);
}
public int getValue3() {
return (mData >>> VAL_3_POSN) & FOUR_BIT_MASK;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof BitTwiddler) {
BitTwiddler rhs = (BitTwiddler)obj;
return this.getValue1() == rhs.getValue1() &&
this.getValue2() == rhs.getValue2() &&
this.getValue3() == rhs.getValue3();
} else {
return false;
}
}
@Override
public int hashCode() {
return (int)mData;
}
@Override
public String toString() {
return "[" + getValue1() + " "
+ getValue2() + " "
+ getValue3() + "]";
}
} // end class BitTwiddler