Representing numbers in byte arrays (Java programming)

I tried to use a two byte array to represent port number 9876 (or 0x2694 in hexadecimal):

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

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

But I got a warning about possible loss of accuracy:

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

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

Note: I chose @ BJ ö RN's code as the correct answer, but @ glowcoder's code also works well This is just another way to solve the same problem Thank you!

Solution

My first answer is bit shifting, but in my second idea, I think using output stream may be better and easier to understand I usually avoid casting spells, but if you're not going to use a general solution, I think it's OK

The above is all the contents of representing numbers in byte array (Java programming) collected by programming house for you. I hope this article can help you solve the program development problems encountered in representing numbers in byte array (Java programming).

If you think the content of the programming home website is good, you are welcome to recommend the programming home website to programmers and friends.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>