安装:
go get github.com/bits-and-blooms/bitset
下面代码把fmtx换成fmt就行
//------------基本操作------------//构建一个64bit长度的bitsetb := bitset.New(64)//放入一个数b.Set(10)fmtx.Println("add-10:", b.DumpAsBits()) // 0000000000000000000000000000000000000000000000000000010000000000//删除一个值b.Set(12)b.Clear(10)fmtx.Println("del-10:", b.DumpAsBits()) //0000000000000000000000000000000000000000000000000001000000000000//测试b.Set(2).Set(6)fmtx.Println("add-2-6:", b.DumpAsBits()) //0000000000000000000000000000000000000000000000000001000001000100fmtx.Println("test2:", b.Test(2), " test5:", b.Test(5)) //[test2: true test5: false]b.Set(2) //重复设置fmtx.Println("test2:", b.Test(2), " adds2:", b.DumpAsBits()) //[test2: true adds2: 0000000000000000000000000000000000000000000000000001000001000100.]//----------------指定位置操作---------------//指定位置操作a := &bitset.BitSet{}a.Set(3)//在指定位置插入0a.InsertAt(3)fmtx.Println("指定位置插入0:", a.DumpAsBits()) //0000000000000000000000000000000000000000000000000000000000010000//在指定位置需改a.SetTo(4, false)fmtx.Println("指定位置4修改false:", a.DumpAsBits()) //0000000000000000000000000000000000000000000000000000000000000000a.Set(63)fmtx.Println("指定位置63修改true:", a.DumpAsBits()) //1000000000000000000000000000000000000000000000000000000000000000a.Set(3).DeleteAt(3) //删除了就全都往右移了fmtx.Println("指定位置3删除:", a.DumpAsBits()) //0100000000000000000000000000000000000000000000000000000000000000a.Set(63)fmtx.Println("再指定位置63:", a.DumpAsBits()) //1100000000000000000000000000000000000000000000000000000000000000//---------------两个bitsets交互----------------k := &bitset.BitSet{}j := &bitset.BitSet{}k.Set(1).Set(3).Set(5)j.Set(7).Set(3).Set(5)//交集fmtx.Println(k.Intersection(j)) //{3,5}//并集fmtx.Println(k.Union(j)) //{1,3,5,7}//差集fmtx.Println(k.Difference(j)) //{1}//全等fmtx.Println(k.Equal(j)) // false//遍历arr := bitset.New(64)arr.Set(1).Set(3).Set(5).Set(7)for i, e := arr.NextSet(0); e; i, e = arr.NextSet(i + 1) {fmtx.Println(i) // 1 3 5 7}
布隆过滤器-假阳性率计算公式
可知在哈希函数的个数k一定的情况下:
- 位数组长度m越大,假阳性率越低;
- 已插入元素的个数n越大,假阳性率越高。