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.
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 ).
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.
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).
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.
(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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With