Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from []byte to int in Go Programming

I need to create a client-server example over TCP. In the client side I read 2 numbers and I send them to the server. The problem I faced is that I can't convert from []byte to int, because the communication accept only data of type []byte.

Is there any way to convert []byte to int or I can send int to the server?

Some sample code will be really appreciated.

Thanks.

like image 708
Emanuel Avatar asked Jun 25 '12 06:06

Emanuel


People also ask

What is a [] byte in Golang?

The byte type in Golang is an alias for the unsigned integer 8 type ( uint8 ). The byte type is only used to semantically distinguish between an unsigned integer 8 and a byte. The range of a byte is 0 to 255 (same as uint8 ).

How do you convert bytes to integers?

A byte value can be interchanged to an int value using the int. from_bytes() function. The int. from_bytes() function takes bytes, byteorder, signed, * as parameters and returns the integer represented by the given array of bytes.

How do you cast to int in Go?

In order to convert string to integer type in Golang, you can use the following methods. You can use the strconv package's Atoi() function to convert the string into an integer value. Atoi stands for ASCII to integer. The Atoi() function returns two values: the result of the conversion, and the error (if any).

Can a byte be an int?

Byte intValue() method in Java with examplesThe intValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as int.


1 Answers

(reposting this answer)

You can use encoding/binary's ByteOrder to do this for 16, 32, 64 bit types

Play

package main  import "fmt" import "encoding/binary"  func main() {     var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}     data := binary.BigEndian.Uint64(mySlice)     fmt.Println(data) } 
like image 109
David Budworth Avatar answered Sep 28 '22 08:09

David Budworth