Sometimes, in a real-world application, we have to create a client-server using TCP. We have to send an integer from the client side and to the server. The issue is converting from a slice of byte to int because the communication only accepts data of type []byte. In today's post, we will provide you with some examples of how to convert []byte
to int and versa.
Example 1: Convert ASCII []byte to int
If []byte is an ASCII byte number, convert it to a string before using the strconv
package Atoi
method to convert string to int.
Package strconv implements conversions to and from string representations of basic data types. func Atoi(s string) (int, error)
: Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.
Here is an example of converting []byte
to string and then string to an int:
package main
import (
"fmt"
"strconv"
)
func main() {
byteSlice1 := []byte{54, 54, 49}
int1, _ := strconv.Atoi(string(byteSlice1))
fmt.Println(int1)
byteSlice2 := []byte{54, 60, 70}
int2, _ := strconv.Atoi(string(byteSlice2))
fmt.Println(int2)
}
Output:
661
0
Example 2: Convert ASCII []byte to int with validation
Noted that the default value return from example 1 is 0. Even when the []byte
can not convert to int, the result still 0 but not error. The below example check if there is any error arise during the convert:
package main
import (
"fmt"
"strconv"
)
func main() {
byteSlice1 := []byte{54, 54, 49}
int1, err := strconv.Atoi(string(byteSlice1))
if err == nil {
fmt.Println(int1)
} else {
fmt.Println("Can not convert this []byte to int")
}
byteSlice2 := []byte{54, 60, 70}
int2, err := strconv.Atoi(string(byteSlice2))
if err == nil {
fmt.Println(int2)
} else {
fmt.Println("Can not convert this []byte to int")
}
}
Output:
661
Can not convert this []byte to int
Example 3: Using math/big package to convert []byte to int
math/big: Package big implements arbitrary-precision arithmetic (big numbers). The following numeric types are supported:
Int signed integers
Rat rational numbers
Float floating-point numbers
The <a href="https://www.golinuxcloud.com/golang-math/">math</a>/big
offers a quick and straightforward method to turn a binary slice into an integer. Let's take a look at the below example:
package main
import (
"fmt"
"math/big"
)
func main() {
byteSlice := []byte{0x01, 0x00, 0x01}
intVal := int(big.NewInt(0).SetBytes(byteSlice).Uint64())
fmt.Printf("Converted int: %v", intVal)
}
Output:
Converted int: 65537
Example 4: Using binary package to convert byte slice to int32
Package binary implements simple translation between numbers and byte sequences and encoding and decoding of varints. Numbers are translated by reading and writing fixed-size values. A fixed-size value is either a fixed-size arithmetic type (bool, int8, uint8, int16, float32, complex64, ...) or an array or struct containing only fixed-size values.
In this example, we will use Read() function to convert byte to int:
func Read(r io.Reader, order ByteOrder, data any) error
: Read reads structured binary data from r into data. Data must be a pointer to a fixed-size value or a slice of fixed-size values. Bytes read from r are decoded using the specified byte order and written to successive fields of the data.
package main
import (
"bytes"
"encoding/binary"
"fmt"
)
func main() {
var myInt int32
b := []byte{0x01,0xFF,0x01, 0xFF} // This could also be a stream
buf := bytes.NewReader(b)
err := binary.Read(buf, binary.BigEndian, &myInt) // Make sure you know if the data is LittleEndian or BigEndian
if err != nil {
fmt.Println("binary.Read failed:", err)
return
}
fmt.Print(myInt)
}
Output:
33489407
Noted that the output is int32, we can easily convert it to int.
Example 5: Using binary package to convert int64 to byte slice
We can use the package in example 4 to convert int to byte slice:
package main
import (
"math/big"
"fmt"
)
func main() {
var value int = 33489407; // int
var int64Val = big.NewInt(int64(value)) // int to big Int
var byteSlice = int64Val.Bytes()
fmt.Println(byteSlice)
}
Output:
[1 255 1 255]
Summary
In this article, I have given some examples of converting byte slice to int using multiple packages. Depending on the specific cases, we can use relevant way as mentioned above.
References
https://pkg.go.dev/strconv
https://pkg.go.dev/math/big