Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int16 to byte array

Tags:

go

I'm trying to convert a int16 to a byte array but i cant seem to get it to work.
Here is what i've got right now:

int16 i := 41
a := []byte(string(i))//this line is wrong

Also if someone wonder the array needs to be a length of 2.

like image 487
Max Avatar asked Jun 23 '13 11:06

Max


People also ask

How do you convert int to bytes?

An int value can be converted into bytes by using the method int. to_bytes().

What is byte array in C#?

In C# a byte array could look like: byte[] bytes = { 3, 10, 8, 25 }; The sample above defines an array of 4 elements, where each element can be up to a Byte in length.

How do you create a byte array in Python?

Python | bytearray() functionbytearray() method returns a bytearray object which is an array of given bytes. It gives a mutable sequence of integers in the range 0 <= x < 256. Returns: Returns an array of bytes of the given size. source parameter can be used to initialize the array in few different ways.

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.


2 Answers

While FUZxxl's answer works, you can also use the encoding/binary package:

var i int16 = 41
b := make([]byte, 2)
binary.LittleEndian.PutUint16(b, uint16(i))

The encoding/binary package has prebuilt functions for encoding little and big endian for all fixed size integers and some easy to use functions if you are using Readers and Writers instead of byte slices. Example:

var i int16 = 41
err := binary.Write(w, binary.LittleEndian, i)
like image 70
Stephen Weinberg Avatar answered Dec 09 '22 21:12

Stephen Weinberg


If you want to get the bytes of an int16, try something like this:

var i int16 = 41
var h, l uint8 = uint8(i>>8), uint8(i&0xff)

Go tries to make it difficult to write programs that depend on attributes of your platform such as byte order. Thence, type punning that leads to such dependencies (such as overlaying a byte-array with an int16) is forbidden.

In case you really want to shoot yourself in the foot, try the package unsafe.

like image 24
fuz Avatar answered Dec 09 '22 20:12

fuz