亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何用Go實現BitSet?

如何用Go實現BitSet?

Go
瀟瀟雨雨 2021-04-09 14:11:29
我沒有在Go中找到BitSet包,所以我嘗試實現它。我想使用uint64數組存儲位。我需要分配uint64數組的位數。使用Java,我可以定義一個接受整數的構造函數。雖然Go不提供構造函數,但是當用戶調用new()時如何正確初始化BitSet'對象'呢?
查看完整描述

3 回答

?
阿波羅的戰車

TA貢獻1862條經驗 獲得超6個贊

如果使用[] uint64切片存儲數據,則零切片可以用作空的BitSet。實際上,附加到nil切片會為您分配一個新數組,盡管Language Specification似乎并不能保證這一點。通過這種設置,new(BitSet)將立即可用。例子:


bitset.go:


package bitset


const size = 64


type bits uint64


// BitSet is a set of bits that can be set, cleared and queried.

type BitSet []bits


// Set ensures that the given bit is set in the BitSet.

func (s *BitSet) Set(i uint) {

    if len(*s) < int(i/size+1) {

        r := make([]bits, i/size+1)

        copy(r, *s)

        *s = r

    }

    (*s)[i/size] |= 1 << (i % size)

}


// Clear ensures that the given bit is cleared (not set) in the BitSet.

func (s *BitSet) Clear(i uint) {

    if len(*s) >= int(i/size+1) {

        (*s)[i/size] &^= 1 << (i % size)

    }

}


// IsSet returns true if the given bit is set, false if it is cleared.

func (s *BitSet) IsSet(i uint) bool {

    return (*s)[i/size]&(1<<(i%size)) != 0

}

bitset_test.go:


package bitset


import "fmt"


func ExampleBitSet() {

    s := new(BitSet)

    s.Set(13)

    s.Set(45)

    s.Clear(13)

    fmt.Printf("s.IsSet(13) = %t; s.IsSet(45) = %t; s.IsSet(30) = %t\n",

               s.IsSet(13), s.IsSet(45), s.IsSet(30))

    // Output: s.IsSet(13) = false; s.IsSet(45) = true; s.IsSet(30) = false

}


查看完整回答
反對 回復 2021-04-26
  • 3 回答
  • 0 關注
  • 384 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號