loop that will output in order from 1 to 5 []bytes in golang

Issue

How to make a loop that will output in order from 1 to 5 []bytes?

Here is what I need in the output:

[0]
[1]
[2]
...
[255]
[0 1]
[1 1]
[2 1]
...
etc (to max 5 bytes)

For example, if I doing a normal loop from numbers and turn them into bytes using these functions:

for i := 0; i < 8589934590; i++ {
    b : intToBytes(i)
    fmt.Println(b)
}

func intToBytes(val int) []byte {
    r := make([]byte, 5)
    for i := int(0); i < 5; i++ {
        r[i] = byte((val >> (8 * i)) & 0xff)
    }
    return r
}

there will be extra zeros at the end of the output.

If this option is correct, then how to get rid of extra zeros?

Solution

Here is a solution. Use append to update the byte slice length. Stop when the shifted result is zero.

package main

import "fmt"

func intToBytes(val int) []byte {
    b := make([]byte, 0, 5)
    for i := range b[:cap(b)] {
        v := val >> (8 * i)
        if v == 0 && i != 0 {
            break
        }
        b = append(b, byte(v))
    }
    return b
}

func main() {
    for i := 0; i < 4; i++ {
        b := intToBytes(i)
        fmt.Println(b)
    }
    fmt.Println("...")
    for i := 260 - 8; i < 260; i++ {
        b := intToBytes(i)
        fmt.Println(b)
    }
    fmt.Println("...")
    for i := 8589934590 - 4; i < 8589934590; i++ {
        b := intToBytes(i)
        fmt.Println(b)
    }
}

https://go.dev/play/p/b91oYBpOw_Y

[0]
[1]
[2]
[3]
...
[252]
[253]
[254]
[255]
[0 1]
[1 1]
[2 1]
[3 1]
...
[250 255 255 255 1]
[251 255 255 255 1]
[252 255 255 255 1]
[253 255 255 255 1]

Answered By – rocka2q

Answer Checked By – Gilberto Lyons (GoLangFix Admin)

Leave a Reply

Your email address will not be published.