bitmap.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package util
  2. import "fmt"
  3. type BitMap struct {
  4. bites []byte
  5. max uint32
  6. curNum int32
  7. }
  8. func NewBitMap(max uint32) *BitMap {
  9. b := make([]byte, (max>>3)+1)
  10. return &BitMap{bites: b, max: max}
  11. }
  12. func (this *BitMap) Add(num uint32) {
  13. if this.max < num {
  14. return
  15. }
  16. index := num >> 3
  17. pos := num & 0x07
  18. this.bites[index] |= 1 << pos
  19. this.curNum++
  20. }
  21. func (this *BitMap) IsExist(num uint32) bool {
  22. if this.max < num {
  23. return false
  24. }
  25. index := num >> 3
  26. pos := num & 0x07
  27. return this.bites[index]&(1<<pos) != 0
  28. }
  29. func (this *BitMap) Remove(num uint32) {
  30. if this.max < num {
  31. return
  32. }
  33. index := num >> 3
  34. pos := num & 0x07
  35. this.bites[index] = this.bites[index] & ^(1 << pos)
  36. this.curNum--
  37. }
  38. func (this *BitMap) Max() uint32 {
  39. return this.max
  40. }
  41. func (this *BitMap) Bites() []byte {
  42. return this.bites
  43. }
  44. //清空原先数据
  45. func (this *BitMap) SetBites(b []byte) {
  46. this.bites = b
  47. this.cntNumProcess()
  48. }
  49. func (this *BitMap) String() string {
  50. return fmt.Sprint(this.bites)
  51. }
  52. func (this *BitMap) CurNum() int32 {
  53. return this.curNum
  54. }
  55. func (this *BitMap) cntNumProcess() {
  56. this.curNum = 0
  57. for idx := 0; idx < len(this.bites); idx++ {
  58. tmpVal := this.bites[idx]
  59. for {
  60. if tmpVal <= 0 {
  61. break
  62. }
  63. if (tmpVal & 1) > 0 {
  64. this.curNum++
  65. }
  66. tmpVal >>= 1
  67. }
  68. }
  69. }