我必须将 3 个字节的数据压缩为两个字节。3 个字节的数据包括一天是一个字节,小时是另一个字节,最后分钟是一个字节。所以我总共有 3 个字节的数据。我怎么能把这个数据只翻转成两个字节。
谢谢,
我必须将 3 个字节的数据压缩为两个字节。3 个字节的数据包括一天是一个字节,小时是另一个字节,最后分钟是一个字节。所以我总共有 3 个字节的数据。我怎么能把这个数据只翻转成两个字节。
谢谢,
要将 3 个字节的数据打包成两个,您必须分派这些位:我将位 0 到 5 设置为分钟,位 6 到 10 设置小时,剩下的位用于天数。
所以打包位的公式是:
packed=minutes+hours*64+days*2048
要取回未压缩的数据:
minutes=packed & 63
hours=(packed & 1984) / 64
days=(packed & 63488) / 2048
我假设您需要 1-31 的一天,0-23 的小时和 0-59 的分钟,因此一天需要 5 位,小时需要 5 位,分钟需要 6 位。这正好是 16 位。您应该将 5 位(天)和前 3 位(小时)放入第一个字节,其余 2 位(小时)和 6 位(分钟)放入第二个字节:
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
希望这可以帮助。很容易弄错位...