位映射简介
如何在一大堆数据中去掉重复数据?我们可以很容易的想到哈希表,通过建立一个与取值范围内每一个数一一对应的哈希表,我们可以很容易的知道一个数是否已经出现,但是如果这堆数据特别大呢?比如说数十亿,取值范围在int的整个范围之间呢?那就需要4 294 967 296个int来存,一个int 4字节,一共需要16gb,这么极其消耗空间,那么有没有更节省空间的方法,考虑到我们对每一位的数据要求只是有没有,用1和0就可以区分,很容易就想到用一个bit来存每一个数字的数据,这就是位映射,当然了,像java,c++中都没有直接的bit类型,所以需要我们自己通过位运算去取。
java实现
首先要说明的是java中自带的实现位映射的类是BitSet类(写完才知道
⊙﹏⊙∥∣°),而且是用Byte实现的(c++中没有byte类),但是无所谓,原理是共通的。先写bitmap,bitset放到(2)写(给自己挖一个坑)。
代码参考:https://blog.csdn.net/xia744510124/article/details/51509285/
https://blog.csdn.net/xqy1522/article/details/7901141
在实现之前,我们需要弄清楚几个简单的位运算技巧:
(1)获取某一位比如0110第二位的值,将其与指定位为1的同位二进制数做与运算,然后再移位0110&0100=0100,0010&0100=0000;0100>>>2=01;
(2)将指定位置1,比如0100第三位:0100|0010=0110
(3)将指定位置0,比如0110第三位:0110&1101(ps:或&~0010)=0100;
public class BitMap {
private int[] bitmap;
private long length;
private int bitValue[]= {
0x80000000,
0x40000000,
0x20000000,
0x10000000,
0x08000000,
0x04000000,
0x02000000,
0x01000000,
0x00800000,
0x00400000,
0x00200000,
0x00100000,
0x00080000,
0x00040000,
0x00020000,
0x00010000,
0x00008000,
0x00004000,
0x00002000,
0x00001000,
0x00000800,
0x00000400,
0x00000200,
0x00000100,
0x00000080,
0x00000040,
0x00000020,
0x00000010,
0x00000008,
0x00000004,
0x00000002,
0x00000001
};
public BitMap() {
this(10000L);
}
public BitMap(long length) {
//计算length长的bit数组需要多大的int数组,1.先右移5位即除32获得大于5位部分
//需要多少int,再判断后五位是否全为0,否则则再加一位,当然处理麻烦可以直接加1
int lengthOfint=(int)(length>>5+((length&31)>0?1:0));
bitValue=new int[lengthOfint];
}
private int getBit(long index) {
//先判断输入
if(length<0) {
throw new IllegalArgumentException("长度必须大于0");
}
//计算想要取得bit所在的int在数组中的序号
int intIndex=(int)(index>>5);
//计算bit值在int中以二进制表示的位数,从左到右
int offset=(int)(index&31);
//取得bit所在int的值
int intData=bitmap[intIndex];
/*用&按位取和取出所求位的值(1或0),但是这个值是包含在int值中的,
* 可以看成是除所求位外的其它值全为0的一个32位二进制数,为直接返
* 回所求值,需要将该值右移,右移位数为该位与最右端距离即31-偏移
* 右移用的是无符号右移>>>而不是右移>>,区别为:
* -1 =11111111111111111111111111111110;
* -1>>5 =11111111111111111111111111111111;
* -1>>>5=111111111111111111111111111;
*/
return (intData&bitValue[offset])>>>(31-offset);
}
public void setBit(long index,int value) {
//先做输入处理
if(index<0||index>length) {
throw new IllegalArgumentException("序号输入有误!");
}
if(value!=0&&value!=1) {
throw new IllegalArgumentException("值必须为0或1");
}
//同上,先命名三个中间值
int intIndex=(int)(index>>5);
int offset=(int)(index&31);
int intData=bitmap[intIndex];
if(value==1) {
//取或,置1
bitmap[intIndex]=intData|bitValue[offset];
}
else {
//取与,置0
bitmap[intIndex]=intData&~bitValue[offset];
}
}
//默认置1
public void setBit(long index) {
this.setBit(index, 1);
}
public long getLength() {
return length;
}
public static void main(String[]args) {
Bit bitmap=new Bit(10000L);
int[] result=new int[100];
for(int i=0;i<100;i++) {
if(Math.random()>0.5) {
bitmap.setBit(i, 1);
result[i]=1;
}
}
Random ra=new Random();
for(int i=0;i<10;i++) {
int temp=ra.nextInt(100);
System.out.println("第"+(temp+1)+"位初始化值为"+result[temp]);
System.out.println("读取中...获得的值为"+bitmap.getBit(temp));
}
}
}