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