bits-and-blooms / bitset

Go package implementing bitsets
BSD 3-Clause "New" or "Revised" License
1.34k stars 175 forks source link

DumpAsBits outputs reversed bit string #152

Closed comunidadio closed 10 months ago

comunidadio commented 10 months ago
package main

import (
    "fmt"

    "github.com/bits-and-blooms/bitset"
)

func main() {
    bs := bitset.New(128)
    bs.Set(1)
    bs.Set(10)
    bs.Set(90)
    fmt.Println(bs.DumpAsBits())
}

Outputs: 0000000000000000000000000000000000000100000000000000000000000000.0000000000000000000000000000000000000000000000000000010000000010.

Expected: 0100000000010000000000000000000000000000000000000000000000000000.0000000000000000000000000010000000000000000000000000000000000000.

lemire commented 10 months ago

The convention in Go, as in most programming languages, is that the least significant bits appear at the end.

E.g., if you set the bit at index 0, a 1 will appear at the last position:

package main

import (
    "fmt"
)

func main() {
    n := int64(1)
    fmt.Printf("%064b", n)
}

Prints:

0000000000000000000000000000000000000000000000000000000000000001

If you want to reverse a string, it is relatively easy to do so in Go:

func Reverse(s string) string {
    r := []rune(s)
    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
        r[i], r[j] = r[j], r[i]
    }
    return string(r)
}