Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert type to byte array golang

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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..!
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading