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.
An int value can be converted into bytes by using the method int. to_bytes().
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.
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.
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
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)
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.
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