-4

I have a short val = 150; how do I put this short into a byte[2]?

I have found some code examples because other people asked these question too, but none of them worked for me well.. please help me

MrTux
  • 32,350
  • 30
  • 109
  • 146
Moritz Schmidt
  • 103
  • 2
  • 6

2 Answers2

3

Try this.

short val = 150;
byte[] result = ByteBuffer.allocate(2).putShort(val).array();
0

You can do this:

short val = 150;
byte []array = new byte[2]
array[0] = (byte)(val & 0xff);
array[1] = (byte)((val >> 8) & 0xff);

You are putting in array[0] the least significant byte. In array[1] the most significant byte.

For more about the meaning of the operations you can read here

granmirupa
  • 2,780
  • 16
  • 27
  • Thank you for your fast answer, if I try this, i get the following output: array[0] = -106 array[1] = 0 this doesnt make sense to me – Moritz Schmidt Oct 11 '16 at 11:36
  • Why not? What's the problem? – granmirupa Oct 11 '16 at 11:45
  • Could you maybe explain me each line of the code ? I really dont get it.. thank you – Moritz Schmidt Oct 11 '16 at 11:47
  • In the array[0] there will be the least significant part of bits. (the least significant byte). In array[1] the most significant. obviously you can invert if you prefer. 0xff means FF in hexdecimal. For more about the meaning you read here: https://oscarliang.com/what-s-the-use-of-and-0xff-in-programming-c-plus-p/ – granmirupa Oct 11 '16 at 11:54
  • Thank you very much. it worked for me all the time I just felt unconfortable with the fact that there were negative numbers in the byte array.. thank you! – Moritz Schmidt Oct 13 '16 at 16:13
  • I just did. Iam sorry Iam new to this forum – Moritz Schmidt Oct 13 '16 at 16:25