Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int to a single byte in Go

Tags:

go

https://github.com/tarm/serial/blob/master/serial.go#L103

type StopBits byte
type Parity byte

type Config struct {
    Name        string
    Baud        int
    ReadTimeout time.Duration
    Size byte
    Parity Parity
    StopBits StopBits
}

I am trying to flag the command line and fill in the config struct but i can't figure out how to go from int or string to a single byte?

example size 7

Tried

mysize := "7"
mysize[0]

but then tarm/serial tells me invalid input error in the serial.Config

i, err := strconv.Atoi("7")

compiler complains that i can't do i.(byte)

The only way I can make it work is to hardcode size: 7 in the config struct.

like image 760
Gert Cuykens Avatar asked Nov 29 '22 09:11

Gert Cuykens


2 Answers

You can just convert an int to a byte: https://play.golang.org/p/w0uBGiYOKP

val := "7"
i, _ := strconv.Atoi(val)
byteI := byte(i)
fmt.Printf("%v (%T)", byteI, byteI)

compiler complains that i can't do i.(byte)

Of course, because that is a type assertion, it will fail if i is not of the given type (byte in your example) or it's not an interface.

like image 162
Duru Can Celasun Avatar answered Dec 04 '22 14:12

Duru Can Celasun


In order to use a type assertion (which you're doing), you need to have an interface on the left. You're likely receiving an error along the lines of "non-interface type byte on left"-- which is true, because you already know the type. Instead, you should be casting.

You'll want to use byte(i) instead of i.(byte):

i := 12
c := byte(i)
fmt.Println(c) //12

Be careful when you have an int that exceeds the max int a byte can hold; you will end up overflowing the byte. In this case, if it's over 255 (the most a single byte can hold), you'll overflow.

like image 28
william.taylor.09 Avatar answered Dec 04 '22 14:12

william.taylor.09