简体   繁体   中英

How to convert type to byte array golang

How to Convert Type of one kind to byte array

Here is the working example

package main

import (
    "bytes"
    "fmt"
    "reflect"
)

type Signature [5]byte

const (
    /// Number of bytes in a signature.
    SignatureLength = 5
)

func main() {

    var bytes0to64 Signature = SignatureFromBytes([]byte("Here is a string.........."))
    fmt.Println(reflect.TypeOf(bytes0to64))

    res := bytes.Compare([]byte("Test"), bytes0to64)
    if res == 0 {
        fmt.Println("!..Slices are equal..!")
    } else {
        fmt.Println("!..Slice are not equal..!")
    }

}

func SignatureFromBytes(in []byte) (out Signature) {
    byteCount := len(in)
    if byteCount == 0 {
        return
    }

    max := SignatureLength
    if byteCount < max {
        max = byteCount
    }

    copy(out[:], in[0:max])
    return
}

In Go lang defined

type Signature [5]byte

So this is expected

var bytes0to64 Signature = SignatureFromBytes([]byte("Here is a string.........."))
    fmt.Println(reflect.TypeOf(bytes0to64))

It just output the Type to

main.Signature

This is correct, now I want to get the byte array from this for the next level of processing and get a compilation error

./prog.go:23:29: cannot use bytes0to64 (type Signature) as type []byte in argument to bytes.Compare

Go build failed.

The error is right only there is a mismatch on comparison. Now how should i convert the Signature type to byte array

Since Signature is a byte array, you may simply slice it:

bytes0to64[:]

This will result in a value of []byte .

Testing it:

res := bytes.Compare([]byte("Test"), bytes0to64[:])
if res == 0 {
    fmt.Println("!..Slices are equal..!")
} else {
    fmt.Println("!..Slice are not equal..!")
}
res = bytes.Compare([]byte{72, 101, 114, 101, 32}, bytes0to64[:])
if res == 0 {
    fmt.Println("!..Slices are equal..!")
} else {
    fmt.Println("!..Slice are not equal..!")
}

This will output (try it on the Go Playground ):

!..Slice are not equal..!
!..Slices are equal..!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM