Go語言實現位元影像排序,go位元影像排序

來源:互聯網
上載者:User

Go語言實現位元影像排序,go位元影像排序

     Go語言提供了byte類型,一個byte對應8個位,所以轉換一下就可以實現位元影像了。

    代碼:    

package main//author:xcl//date:2014-1-25import ("fmt")func main() {arrInt32 := [...]uint32{5, 4, 2, 1, 3, 17, 13}var arrMax uint32 = 20bit := NewBitmap(arrMax)for _, v := range arrInt32 {bit.Set(v)}fmt.Println("排序後:")for i := uint32(0); i < arrMax; i++ {if k := bit.Test(i); k == 1 {fmt.Printf("%d ", i)}}}const (BitSize = 8 //一個位元組8位)type Bitmap struct {BitArray  []byteArraySize uint32}func NewBitmap(max uint32) *Bitmap {var r uint32switch {case max <= BitSize:r = 1default:r = max / BitSizeif max%BitSize != 0 {r += 1}}fmt.Println("數組大小:", r)return &Bitmap{BitArray: make([]byte, r), ArraySize: r}}func (bitmap *Bitmap) Set(i uint32) {idx, pos := bitmap.calc(i)bitmap.BitArray[idx] |= 1 << posfmt.Println("set()  value=", i, " idx=", idx, " pos=", pos, ByteToBinaryString(bitmap.BitArray[idx]))}func (bitmap *Bitmap) Test(i uint32) byte {idx, pos := bitmap.calc(i)return bitmap.BitArray[idx] >> pos & 1}func (bitmap *Bitmap) Clear(i uint32) {idx, pos := bitmap.calc(i)bitmap.BitArray[idx] &^= 1 << pos}func (bitmap *Bitmap) calc(i uint32) (idx, pos uint32) {idx = i >> 3 //相當於i / 8,即位元組位置if idx >= bitmap.ArraySize {panic("數組越界.")return}pos = i % BitSize //位位置return}//ByteToBinaryString函數來源:// Go語言版byte變數的二進位字串表示// http://www.sharejs.com/codes/go/4357func ByteToBinaryString(data byte) (str string) {var a bytefor i := 0; i < 8; i++ {a = datadata <<= 1data >>= 1switch a {case data:str += "0"default:str += "1"}data <<= 1}return str}
運行結果:

  

數組大小: 3set()  value= 5  idx= 0  pos= 5 00100000set()  value= 4  idx= 0  pos= 4 00110000set()  value= 2  idx= 0  pos= 2 00110100set()  value= 1  idx= 0  pos= 1 00110110set()  value= 3  idx= 0  pos= 3 00111110set()  value= 17  idx= 2  pos= 1 00000010set()  value= 13  idx= 1  pos= 5 00100000排序後:1 2 3 4 5 13 17

MAIL:  xcl_168@aliyun.com

BLOG: http://blog.csdn.net./xcl168



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.