Skip to main content
deleted 36 characters in body; edited tags
Source Link
Jamal
  • 35.2k
  • 13
  • 134
  • 238

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.

Here's the code I have so far.:

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... isIs there a more intuitive way to write this in Go?

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.

Here's the code I have so far.

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?

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?

Source Link
Kevin Burke
  • 617
  • 2
  • 6
  • 11

Pad a function with random bytes

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.

Here's the code I have so far.

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?