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.
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).
toArray(): Guava Ints. toArray() can be used to convert set of integer to an array of integer.
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.
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) }
Check out the "encoding/binary" package. Particularly the Read and Write functions:
binary.Write(a, binary.LittleEndian, myInt)
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