func Encode(dst, src []byte) int
is a method defined in the encoding packages in Golang that encodes source bytes of an array to a destination bytes array and returns the number of bytes written in the encoded array. The type of encoding depends on which Golang package is used. func Encode(dst, src []byte) int
is defined in the following Golang packages:
encoding/ascii85
encoding/asn1
encoding/base32
encoding/base64
encoding/binary
encoding/csv
encoding/gob
encoding/hex
encoding/json
encoding/pem
encoding/xml
src
: Array of type byte
.
dst
: Array to which the encoded output will be written.
The number of bytes written to dst
.
package mainimport ("encoding/hex""fmt")func main() {src := []byte("Hexadecimal encoding in Golang.")dst := make([]byte, hex.EncodedLen(len(src)))var bytes_written int = hex.Encode(dst, src)fmt.Printf("Encoded array: %s\n", dst)fmt.Printf("Number of bytes written: %d\n", bytes_written)}
In the above example, we initialize the src
bytes array that stores the bytes of the string “Hexadecimal encoding in Golang”. We initialize the dst
array with the size that will result after encoding.
The method hex.EncodedLen()
returns the size of the encoded array. Then, we use hex.encode()
, which encodes the src
array and writes the encoded result in dst
, and returns the number of bytes written.
Free Resources