安装:
go get github.com/bits-and-blooms/bitset
下面代码把fmtx换成fmt就行
//------------基本操作------------
//构建一个64bit长度的bitset
b := 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()) //0000000000000000000000000000000000000000000000000001000001000100
fmtx.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)
//在指定位置插入0
a.InsertAt(3)
fmtx.Println("指定位置插入0:", a.DumpAsBits()) //0000000000000000000000000000000000000000000000000000000000010000
//在指定位置需改
a.SetTo(4, false)
fmtx.Println("指定位置4修改false:", a.DumpAsBits()) //0000000000000000000000000000000000000000000000000000000000000000
a.Set(63)
fmtx.Println("指定位置63修改true:", a.DumpAsBits()) //1000000000000000000000000000000000000000000000000000000000000000
a.Set(3).DeleteAt(3) //删除了就全都往右移了
fmtx.Println("指定位置3删除:", a.DumpAsBits()) //0100000000000000000000000000000000000000000000000000000000000000
a.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越大,假阳性率越高。