Working with 'nibbles' in java
Hi, Im storing values in bytes containing two nibbles (4 bits) packed into a vector of bytes. I have two values between 0 and 15 for each nibble, I create two bytes and set each value to these, I then shift the first byte 4 places and and add the result to the second byte to creat the final resulting byte containing two nibbles. Here are two snippets of code from seperate methods:
//to create a byte from two nibbles
//this takes two byte from a vector (in which only the right half has a nibble, the left is 4 zeros: 0000-nibble)
firstHalfByte = ((Byte)(tempResult.get(position))).byteValue();
firstHalfByte = (byte)(firstHalfByte << 4);
secondHalfByte = ((Byte)(tempResult.get(position+1))).byteValue(); //not shifted as above
resultByte = (byte)(firstHalfByte + secondHalfByte);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//to extract nibbles from byte vector
byte firstHalfMask = (byte)11110000;
byte secondHalfMask = (byte)00001111;
currentByte = ((Byte)(v.get(i))).byteValue(); //get byte from vector
firstHalf = (byte)((currentByte * firstHalfMask) >> 4);
secondHalf = (byte)(currentByte * secondHalfMask);
////////////////////////////////////////////////////////////////////////////////////////////////
I printed an example out on to the console and got the byte's values
firstHalf: 15
second half: 5
result: -11
In my head it should work out like this:
00001111 (15)00000101 (5)
1111000000000101
result: 11110101
when the application attempts to extract the nibbles from -11 it gets
currentByte = -11
firstHalf = -77
secondHalf = -35
If I can somehow make it retrieve 15 and 5 from -11 I'd be very happy. Im guessing its some this to do with the fact that java treats a byte as signed? Surely it should not matter when shifting bits since they're simply binary numbers so it shouldn't matter how java interprets them?
Thanks for your time.

