再$ P $字节数组psenting一个数字(Java编程) [英] Representing a number in a byte array (java programming)

查看:117
本文介绍了再$ P $字节数组psenting一个数字(Java编程)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图重新present在两个字节数组的端口号9876(或0x2694十六进制):

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;
     }
}

但我得到一个约precision可能丢失警告:

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

我怎样才能重新present不失precision在两字节数组数9876?

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

注意:我选择了code。通过@比约恩为正确答案,而是通过@焕发$ C $的code CR也是行之有效的。这只是一种不同的方法,以同样的问题。谢谢大家!

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!

推荐答案

我的第一个答案会是bitshifting,但在第二次思想我认为使用outputstreams可以更好,更简单易懂。我通常会避免铸造,但如果你不打算为一个通用的解决方案我想这会好起来的。 :)

My first answer would be bitshifting, but on a second thought I think using outputstreams could be better and more simple to understand. I usually avoid casting, but if you're not going for a generic solution I guess that would be okay. :)

使用流,一个通用的解决方案:

Using streams, a generic solution:

public byte[] intToByteArray(final int i) throws java.io.IOException {
    java.io.ByteArrayOutputStream b = new java.io.ByteArrayOutputStream();
    java.io.DataOutputStream d = new java.io.DataOutputStream(b);
    d.writeInt(i);
    d.flush();

    return b.toByteArray();
}

和扭转它:

public int byteArrayToInt(final byte[] b) throws IOException {
    java.io.ByteArrayInputStream ba = new java.io.ByteArrayInputStream(b);
    java.io.DataInputStream d = new java.io.DataInputStream(ba);

    return d.readInt();
}

这篇关于再$ P $字节数组psenting一个数字(Java编程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆