doudun5009
2019-08-13 19:33 阅读 148
已采纳

遍历字节数组的所有值

I'm trying to loop through all values of a small byte array (64 bytes). I want to increment the way a digital clock would, start at index 0, go 0-255 then increment index 1, repeat. I know this is probably a recursion method, but I can't wrap my head around the logic.

So basically, for a 4 byte array (smaller for convenience)

Round 1

value: [0 0 0 0]

Round 256

value [ 255 0 0 0]

Round 256

value [ 0 1 0 0 ]

Round 257

value [ 1 1 0 0 ]

What I have so far:

func allValues() {
    currentPlaceIndex := 0
    content := make([]uint8, 64)
    max := 256

    for i := 0; i < max; i++ {
        content[currentPlaceIndex] = uint8(i)
    }
    fmt.Println(content)
    content[currentPlaceIndex] = 0

}

I can't seem to figure out how to recurse this.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dongzhuohan7085 dongzhuohan7085 2019-08-13 19:45

    Converting round number to byte array

    This representation is basically the base 256 radix. The first byte will be the round number % 256. Then divide the round number by 256, and repeat until the round number becomes 0.

    Since 256 is a special number (256 = 28), you may use bitwise operations for the calculations. E.g. the remainder is equal to bitmasking with 0xff, and the division by 256 is equal to shifting right by 8.

    Also note that there is a big.Int type in the standard library which represents a (signed) multi-precision integer. And it has an Int.Bytes() method which returns the absolute value as a big-endian byte slice. This is "almost" what we want, it's just in different byte order. So you may simply convert a round number to big.Int (e.g. using the Int.SetString() method), get its byte slice and reverse it.

    Iterating over the values

    If you don't want to convert a single round number but just iterate over the subsequent values, then do it like this:

    1. You start with a full zero slice or array.

    2. Check the first element of the slice. If < 255, simply increment it by one. Done with the iteration.

    3. If it was 255, zero it, and attempt to do the same with the 2nd element: go to step 2.

    So if you have a state, this is how you can calculate the next one:

    func next(data []byte) {
        for idx := range data {
            if data[idx] < 255 {
                data[idx]++
                return
            }
            data[idx] = 0
        }
        fmt.Println("overflow")
    }
    

    This is how you can test it:

    data := make([]byte, 64)
    for iter := 0; iter < 600; iter++ {
        next(data)
        fmt.Println(data)
    }
    

    This will output (try it on the Go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