int型32位压缩
之前看到有个人问如何读取文件,文件中的数字为0~1024的数字,int型存储是默认32位。想以12位进行压缩。
利用晚上时间写了个main方法进行,顺便进行了测试。原理很简单就是每隔12位存储,多余就补位。
以前对java的位移不是很了解,因为不是本专业的,后来进入it圈发展。自己写的玩的。如果谁能用到就拿去看看吧。代码应该可以优化,由于比较懒就算了。
public static void main(String[] args) {
int[] is = {1, 3, 4, 5, 7, 9, 11, 1, 1, 5, 1, 1, 1};
List<Integer> newis = new ArrayList<Integer>();
int temp1 = 0;
int tempi = 0; // 余量
int tempj = 0; // 需量
int tempm = 0; // 总位数
boolean canadd = false;
for (int i = 0; i < is.length; i++) {
if (tempj != 0) {
i--;
temp1 = is[i] >> tempi;
tempm = tempm + tempj;
tempj = 0;
tempi = 0;
continue;
}
if (tempm % 32 == 0) {
temp1 = is[i];
tempm+=12;
if (i == is.length - 1) {
newis.add(is[i]);
}
continue;
}
if (tempm + 12 >= (newis.size() + 1)*32) {
tempi = 32 - tempm%32;
tempj = 12 - tempi;
temp1 = temp1 | is[i] << (32 - tempi);
tempm = tempm + tempi;
canadd = true;
} else {
temp1 = temp1 | is[i] << tempm % 32;
tempm += 12;
}
if (canadd) {
newis.add(temp1);
canadd = false;
} else if (i == is.length - 1) {
newis.add(temp1);
}
}
// 解压过程
for (int i = 0; i < newis.size(); i++) {
// 自己写吧
}
}