Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Representing a number in a byte array (java programming)

I'm trying to represent the port number 9876 (or 0x2694 in hex) in a two byte array:

class foo {
     public static void main (String args[]) {
   byte[] sendData = new byte[1];

   sendData[0] = 0x26;
   sendData[1] = 0x94;
     }
}

But I get a warning about possible loss of precision:

foo.java:5: possible loss of precision
found   : int
required: byte
   sendData[1] = 0x94;
                 ^
1 error

How can I represent the number 9876 in a two byte array without losing precision?

NOTE: I selected the code by @Björn as the correct answer, but the code by @glowcoder also works well. It's just a different approach to the same problem. Thank you all!

like image 910
Mark Roberts Avatar asked May 19 '10 19:05

Mark Roberts


1 Answers

Have you tried casting to a byte ? e.g.

sendData[1] = (byte)0x94;
like image 68
Brian Agnew Avatar answered Oct 10 '22 03:10

Brian Agnew