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)
}
Answer from David Budworth on Stack Overflow
🌐
Bacancy Technology
bacancytechnology.com › qanda › golang › how-to-convert-from-byte-to-int-in-go
How to convert from []byte to int in Go Programming
September 15, 2023 - This package provides functions to convert between strings and various data types, including integers. Here’s an example of how you can use strconv to convert a []byte to an int:
🌐
GoLinuxCloud
golinuxcloud.com › home › programming › golang › golang byte to int: convert `byte` and `[]byte` correctly
Golang byte to int and []byte to int: strconv, binary, big.Int
October 21, 2022 - A single byte is just uint8 and converts with int(b). A []byte has no single integer meaning: it might hold decimal text, fixed-width binary, a varint, or a large unsigned magnitude.
People also ask

How do I convert a single byte to int in Go?
byte is an alias for uint8. Widen with int(b); the numeric value stays in the 0–255 range. This applies to one byte only, not to a []byte slice.
🌐
golinuxcloud.com
golinuxcloud.com › home › programming › golang › golang byte to int: convert `byte` and `[]byte` correctly
Golang byte to int and []byte to int: strconv, binary, big.Int
How do I convert four bytes to an int32 or uint32?
Use binary.BigEndian.Uint32(buf) or binary.LittleEndian.Uint32(buf) when you know the width and byte order. Cast to int32 for signed two-complement bits. Validate len(buf) before slicing.
🌐
golinuxcloud.com
golinuxcloud.com › home › programming › golang › golang byte to int: convert `byte` and `[]byte` correctly
Golang byte to int and []byte to int: strconv, binary, big.Int
How do I convert []byte("123") to an integer?
When the slice holds decimal text, use strconv.Atoi(string(b)) or strconv.ParseInt with an explicit base and bit size. Always check the returned error.
🌐
golinuxcloud.com
golinuxcloud.com › home › programming › golang › golang byte to int: convert `byte` and `[]byte` correctly
Golang byte to int and []byte to int: strconv, binary, big.Int
🌐
Reddit
reddit.com › r/golang › converting bytes to integers
r/golang on Reddit: Converting bytes to integers
July 20, 2016 -

Hi everyone,

I just started using Go today, and am having trouble converting bytes read from a file into integers. I usually code in higher level languages like Python and JavaScript.

I've already seen several StackOverflow threads on this but they're fairly old and none of the suggestions have worked so far.

Specifically, what I'm trying to do is read a BigEndian 16bit signed integer. I'll also need to read int8, int32, and Uint8 eventually.

I've tried using:

binary.Read

binary.ReadVarunt

binary.Varint

For example:

f, _ := os.Open(filePath)
b1 := make([]byte, 2)
_, _ = f.Read(b1)
buf := bytes.NewReader(b1)

var i int16
_ = binary.Read(buf, binary.BigEndian, &i)
fmt.Printf("Int: %s\n", string(i))

f.Close()

And it always just prints weird symbols or blanks when outputting using fmt.Printf

For comparison, in JavaScript I would create a DataView on my file and then just use methods like getInt16() and it works fine.

In Python 3 I would use int.from_bytes(bytes_list, byteorder='big')

So what am I missing?

🌐
Go Forum
forum.golangbridge.org › getting help
Converting single-byte slice to int - Getting Help - Go Forum
April 2, 2018 - In my program I need to read data from the byte array, sometimes I need to read single byte, sometimes 2, 4 or 8 bytes. Then these bytes should be converted into “normal” integer values. For 2, 4 and 8 bytes I can use “encodings/binary” package and its binary.BigEndian.Uint16(), binary.BigEndian.Uint32() and binary.BigEndian.Uint64() and then cast values to int if necessary.
Top answer
1 of 12
82

I agree with Brainstorm's approach: assuming that you're passing a machine-friendly binary representation, use the encoding/binary library. The OP suggests that binary.Write() might have some overhead. Looking at the source for the implementation of Write(), I see that it does some runtime decisions for maximum flexibility.

func Write(w io.Writer, order ByteOrder, data interface{}) error {
    // Fast path for basic types.
    var b [8]byte
    var bs []byte
    switch v := data.(type) {
    case *int8:
        bs = b[:1]
        b[0] = byte(*v)
    case int8:
        bs = b[:1]
        b[0] = byte(v)
    case *uint8:
        bs = b[:1]
        b[0] = *v
    ...

Right? Write() takes in a very generic data third argument, and that's imposing some overhead as the Go runtime then is forced into encoding type information. Since Write() is doing some runtime decisions here that you simply don't need in your situation, maybe you can just directly call the encoding functions and see if it performs better.

Something like this:

package main

import (
    "encoding/binary"
    "fmt"
)

func main() {
    bs := make([]byte, 4)
    binary.LittleEndian.PutUint32(bs, 31415926)
    fmt.Println(bs)
}

Let us know how this performs.

Otherwise, if you're just trying to get an ASCII representation of the integer, you can get the string representation (probably with strconv.Itoa) and cast that string to the []byte type.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    bs := []byte(strconv.Itoa(31415926))
    fmt.Println(bs)
}
2 of 12
40

Check out the "encoding/binary" package. Particularly the Read and Write functions:

binary.Write(a, binary.LittleEndian, myInt)
🌐
Reddit
reddit.com › r/golang › bytes -> int
r/golang on Reddit: bytes -> int
July 6, 2023 -

Hi,I am trying to rewrite some python lines to golang and I am stuck on converting byte array to int (little-endian byteorder)

python:

bytes1 = [84, 48, 92]
bytes2 = [84, 48, 92, 91, 244]
num1 = int.from_bytes(bytes1, "little")
print(f"num1: ", num1)
num2 = int.from_bytes(bytes2, "little")
print(f"num2: ", num2)

gives me output:

num1: 6041684
num2: 1049504788564

and in golang :

`bytes1 := []byte{84, 48, 92}`  
`bytes2 := []byte{84, 48, 92, 91, 244}`  
`num1 := int(binary.LittleEndian.Uint16(bytes1))`  
`fmt.Println("num1:", num1)`  
`num2 := int(binary.LittleEndian.Uint32(bytes2))`  
`fmt.Println("num2:", num2)`

I get:
num1: 12372
num2: 1532768340

can someone tell me what am I doing wrong ?

🌐
Reddit
reddit.com › r/golang › converting []byte to int32
r/golang on Reddit: Converting []byte to int32
August 14, 2016 -

I'm reading bytes from a file (image pixel data) and need to parse integers. Currently doing it with an io.Reader on the file and it works fine, but I also want to be able to parse []byte directly.

int8, uint8, int16, and uint16 are easy but I'm having trouble parsing int32 and uint32.

For example, I have this byte array: [56 66 73 77]

The parsed int32 should be 334244, big endian.

Using the aforementioned io.Reader works:

r := bufio.NewReader(file)
var num int32
binary.Read(r, binary.BigEndian, &num )

But converting the bytes directly doesn't work, it yields 943868237 instead of the expected 334244

int32(binary.BigEndian.Uint32(bytes))

Same with this method:

int32(b[3]) + (int32(b[2]) << 8) + (int32(b[1]) << 16) + (int32(b[0]) << 24)

Same with using a Reader on the bytes slice:

r := bytes.NewReader(bytes)
var num int32
binary.Read(1, binary.BigEndian, &num)

I'm used to working in higher level languages like Python and JavaScript so I might be missing something obvious. Any help is much appreciated.

Find elsewhere
🌐
GitHub
gist.github.com › ecoshub › 5be18dc63ac64f3792693bb94f00662f
golang integer to byte array and byte array to integer function · GitHub
The order of the bytes is reversed. output for 22233 is [217 86 0 0 0 0 0 0] but should be [0 0 0 0 0 0 86 217] fmt.Printf("%v\n", IntToByteArray(int64(22233))) fmt.Printf("%v\n", big.NewInt(int64(22233)).Bytes()) fmt.Printf("%d\n", ByteArrayToInt(big.NewInt(int64(22233)).Bytes())) // Outputs: [217 86 0 0 0 0 0 0] [86 217] 55638
🌐
Google Groups
groups.google.com › g › golang-nuts › c › od-7GC3l1To
[go-nuts] []byte to int32
On Apr 21, 4:28 pm, Roger Pau Monné <roy...@gmail.com> wrote: > You could use something like: > > number := uint32(byte[0]) | (uint32(byte[1]) << 8) | (uint32(byte[2]) << 16) > | .... > > The encoding/binary package has some examples.
🌐
Google Groups
groups.google.com › g › Golang-Nuts › c › se5SRGw3kqQ
Converting byte array into Integer
October 29, 2013 - ... Either email addresses are ... AM, Abhinav Srivastava <abhi1988s...@gmail.com> wrote: If a byte array has to be interpreted as an integer then it's effectively just a number (sequence of digits) in base 256 (every byte is a single digit in that base)....
🌐
Go Forum
forum.golangbridge.org › getting help
Converting byte array to signed int - Getting Help - Go Forum
August 29, 2022 - Hi, I have for example the following codes. What it does it take the hex string convert into byte array then I would like to convert to its relevant int value. The issue it doesnt give the signed version of the integer. In this case the value should be -12269766 but I keep getting as 1717974068.
🌐
Go Packages
pkg.go.dev › github.com › saman-org › go-saman › common › bytesutil
bytesutil package - github.com/saman-org/go-saman/common/bytesutil - Go Packages
April 17, 2021 - FromBytes8 returns an integer which is stored in the little-endian format(8, 'little') from a byte array. ... LowerThan returns true if byte slice x is lower than byte slice y. (little-endian format) This is used in spec to compare winning block root hash.
🌐
Cyeam
blog.cyeam.com › hash › 2014 › 07 › 29 › go_bytearraytoint
Golang binary package - how to convert byte array to int?
July 29, 2014 - package main import "fmt" import "encoding/binary" func main() { var a []byte = []byte{0, 1, 2, 3} fmt.Println(a) fmt.Println(binary.BigEndian.Uint32(a)) fmt.Println(binary.LittleEndian.Uint32(a)) }
🌐
Grokbase
grokbase.com › t › gg › golang-nuts › 147b9p4xpj › go-nuts-converting-from-byte-to-int
[go-nuts] Converting from []byte to int - Grokbase
July 11, 2014 - Here's the link to the playground ... runtime.GOOS, runtime.Version(), "input:", input) fmt.Println(toInt(input)) fmt.Println(toInt2(input)) } func toInt(bytes []byte) int { var value int32 = 0 // initialized...