基于uint32的BitMap类库

package tools

import (
	"fmt"
	"strconv"
)

type BitMapTool struct {
	Capacity int64
	BitMapLength int64
	BitMapArray []uint32
}

//region 初始化指定容量的BitMap,使用uint32类型的数组
func (this *BitMapTool) Init(capacity int64){
	this.Capacity=capacity
	this.BitMapLength=int64((capacity+31)/32)
	fmt.Printf("定义BitMap,容量:%d,数组长度:%d\n",capacity,this.BitMapLength)
	this.BitMapArray=make([]uint32,this.BitMapLength)
}
//endregion

//region 设置第N个位置的值为1,即true
func (this *BitMapTool) SetValue(key int64,value bool){
	idx:=uint32((key-1)/32)
	pos:=uint32((key-1) % 32)

	var oldArrayValue,newArrayValue uint32
	oldArrayValue=this.BitMapArray[idx]
	fmt.Printf("数组位置:%d,原值:%d,二进制值:%s\n",idx,oldArrayValue,this.ConverToBianry(oldArrayValue))

	if value{
		newArrayValue=((uint32(1) << pos)|oldArrayValue)
	}else{
		newArrayValue=(uint32(0)&oldArrayValue)|
	}

	fmt.Printf("数组位置:%d,新值:%d,二进制值:%s\n",idx,newArrayValue,this.ConverToBianry(newArrayValue))

	this.BitMapArray[idx]=newArrayValue
}
//endregion


//region 取出第N个位置的bit位的值,判断该值是否存在,true为存在,false为不存在
func (this *BitMapTool) GetValue(value int64)(ret bool){
	idx:=uint32((value-1)/32)
	pos:=uint32((value-1) % 32)

	var oldArrayValue uint32
	oldArrayValue=this.BitMapArray[idx]
	fmt.Printf("数组位置:%d,当前值:%d,二进制值:%s\n",idx,oldArrayValue,this.ConverToBianry(oldArrayValue))

	retstr:="不存在"
	newValue:=(uint32(1) << pos)&oldArrayValue
	if(newValue==0){
		ret=false
	}else{
		ret=true
		retstr="存在"
	}
	fmt.Printf("数组位置:%d,与1<<%d的与计算值:%d,二进制值:%s,结论:%t-%s\n",idx,pos,newValue,this.ConverToBianry(newValue),ret,retstr)
	return ret
}
//endregion

//region 将整型数值转换为二进制字符串
func (this *BitMapTool) ConverToBianry(n uint32) string {
	result := ""
	for ; n > 0; n /= 2 {
		lsb := int(n % 2)
		result = strconv.Itoa(lsb) + result
	}
	return result
}

//endregion

  

上一篇:Hbase从入门到精通,精心整理的学习笔记,自学党快来瞅一瞅,赶紧收藏吧!


下一篇:redis - pipe/pubsub/bloom