Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an integer to a byte array

I have a function which receives a []byte but what I have is an int, what is the best way to go about this conversion ?

err = a.Write([]byte(myInt)) 

I guess I could go the long way and get it into a string and put that into bytes, but it sounds ugly and I guess there are better ways to do it.

like image 837
vascop Avatar asked Jun 02 '13 23:06

vascop


People also ask

Can we convert int to byte in Java?

The byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte).

Can integer convert to array?

toArray(): Guava Ints. toArray() can be used to convert set of integer to an array of integer.

Can we convert int to array in Java?

Just use % 10 to get the last digit and then divide your int by 10 to get to the next one. int temp = test; ArrayList<Integer> array = new ArrayList<Integer>(); do{ array. add(temp % 10); temp /= 10; } while (temp > 0); This will leave you with ArrayList containing your digits in reverse order.


2 Answers

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) } 
like image 67
dyoo Avatar answered Nov 12 '22 19:11

dyoo


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

binary.Write(a, binary.LittleEndian, myInt) 
like image 28
Brainstorm Avatar answered Nov 12 '22 19:11

Brainstorm