2
\$\begingroup\$

I'm writing a function to append 5-10 bytes (count is random) at the beginning of a byte array, and 5-10 random bytes at the end:

func padWithRandomBytes(b []byte) []byte {
 startBytes := make([]byte, 10-rand.Intn(5))
 endBytes := make([]byte, 10-rand.Intn(5))
 newSlice := make([]byte, len(startBytes)+len(b)+len(endBytes))
 copy(newSlice[:len(startBytes)], startBytes)
 copy(newSlice[len(startBytes):len(startBytes)+len(b)], b)
 copy(newSlice[len(startBytes)+len(b):], endBytes)
 return newSlice
}

This feels pretty inefficient. Is there a more intuitive way to write this in Go?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked May 5, 2013 at 2:52
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

For example,

package main
import (
 "fmt"
 "math/rand"
 "time"
)
func padWithRandomBytes(b []byte) []byte {
 s := 5 + rand.Intn(5+1)
 e := 5 + rand.Intn(5+1)
 r := make([]byte, s+len(b)+e)
 copy(r[s:], b)
 return r
}
func main() {
 rand.Seed(time.Now().UnixNano())
 b := []byte{1, 2, 3}
 fmt.Println(len(b), b)
 r := padWithRandomBytes(b)
 fmt.Println(len(r), r)
}

Output (random):

3 [1 2 3]
20 [0 0 0 0 0 0 0 0 1 2 3 0 0 0 0 0 0 0 0 0]
3 [1 2 3]
15 [0 0 0 0 0 0 1 2 3 0 0 0 0 0 0]
answered May 5, 2013 at 11:38
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.