Reputation: 986
For some reason, I couldn't find any answer to this question on StackOverflow. If it's already been answered, kindly point me to a duplicate post. Thanks!
I have a device that delta encodes a signal and packs 2 4-bit deltas into a byte
. I'm trying to decode the signal in Java by separating the upper and lower 4 bits of the byte
into two separate, signed ints
.
For example:
byte packedByte = (byte) 0x0FF; // should represent the value -1, -1 in twos complement
int upper = packedByte >> 4; // upper byte is easy, prints -1
/*
* A few goes at getting the lower 4 bits:
*/
int lower = packedByte & 0x0F; // sign is not extended, prints 15
lower = (packedByte << 4) >> 4; // doesn't work for positive values
lower = (byte)((byte)(packedByte << 4) >>> 4); // works, but this feels slow
Any ideas?
Upvotes: 0
Views: 45
Reputation: 3826
Assuming, as Jim Garrison points out, your nibbles really only represent -8 up to positive 7, you can keep doing what you were doing tof the upper, and you can do the following for the lower: (packedByte & 0x0F)-2*(packedByte & 0x08)
. The logic here is that it leaves 0 to 7 alone (subtracts 0 from it), but if there is a 1 in the sign bit of the lower number, it subtracts 2*8 which is 16 to get the appropriate negative number.
Upvotes: 1