Home > Net >  How to convert type to byte array golang
How to convert type to byte array golang

Time:03-16

How to Convert Type of one kind to byte array

Here is the working example

// You can edit this code!
// Click here and start typing.
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

CodePudding user response:

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..!
  • Related