how to compress the three bytes data into two bytes in java

540 Views Asked by At

I have to compress the 3 bytes of data in to two bytes. the 3 bytes data includes day is in one byte,hour is in another byte, finally minutes is in one more byte.so totally i have 3 bytes data.how could i flip this data into two bytes only.

Thanks,

2

There are 2 best solutions below

1
On
  • Minutes are ranging from 0 to 59 so the number could be stored on 6 bits (6 bits => 0 to 63)
  • Hours are ranging from 0 to 23 the number could be stored on 5 bits (5 bits => 0 to 31)
  • Days... Err... Ranging from 0 to 6 ? Let's asusme that. 2 bytes = 16 bits, minus the 11 other bits, so you have 5 bits left which is more than enough.

To pack your 3 bytes of data into two, you have to dispatch the bits : I will set bits 0 to 5 for the minutes, bits 6 to 10 for the hours, and the bits left for the day number.

So the formula to pack the bits is :

packed=minutes+hours*64+days*2048

To get back your uncompressed data :

minutes=packed & 63
hours=(packed & 1984) / 64
days=(packed & 63488) / 2048
3
On

I assume you need day from 1-31, hour from 0-23 and minute from 0-59, you thus need 5 bits for the day, 5 bits for the hours and 6 bits for the minutes. This makes exactly 16 bits. You should put 5 bits (day) and the first 3 bits for hours into your first byte and the remaining 2 bits for hours and the 6 bits for minutes into the second byte:

 int day = 23;
 int hour = 15;
 int minute = 34;
 byte fromint_dh = (day << 3) | (hour >> 2);
 byte fromint_hm = ((hour & 0x03) << 6) | (minute); // take the last two bits from hour and put them at the beginning

 ....
 int d = fromint_dh >> 3;
 int h = ((fromint_dh & 0x07) << 2) | ((fromint_hm & 0xc0) >> 6); // take the last 3 bits of the fst byte and the fst 2 bits of the snd byte
 int m = fromint_hm & 0x3F // only take the last 6 bits

Hope this helps. It's easy to get the bits wrong ...