表示字节数组中的数字(java编程)

发布于 2024-09-01 20:14:13 字数 517 浏览 3 评论 0原文

我试图在两字节数组中表示端口号 9876(或十六进制的 0x2694):

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

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

但我收到有关可能丢失精度的警告:

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

如何在两字节数组中表示数字 9876 而不会丢失精度?

注意:我选择了 @Björn 的代码作为正确答案,但 @glowcoder 的代码也运行良好。这只是解决同一问题的不同方法。谢谢大家!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

回心转意 2024-09-08 20:14:13

您是否尝试过转换为字节?例如

sendData[1] = (byte)0x94;

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

sendData[1] = (byte)0x94;
老旧海报 2024-09-08 20:14:13

0x94十进制表示为148,超出了java中byte的范围(-128到127)。
您可以执行以下操作之一:

1) 强制转换可以正常工作,因为它将保留二进制表示形式(0x00 到 0xFF 不会截断任何有意义的位):

 sendData[1] = (byte)0x94; 

2) 0x94 作为有符号字节的二进制表示形式是 -108 (- 0x6C),因此以下内容将具有相同的效果:

sendData[1] = -0x6C; //or -108 in decimal

0x94 is 148 in decimal, which exceeds the range of byte in java (-128 to 127).
You can do one of the following:

1) A cast will work fine because it will preserve the binary representation (no meaningful bits are truncated for 0x00 to 0xFF):

 sendData[1] = (byte)0x94; 

2) The binary representation of 0x94 as a signed byte is -108 (-0x6C), so the following will have the same effect:

sendData[1] = -0x6C; //or -108 in decimal
无悔心 2024-09-08 20:14:13

Björn 对于使用流给出了一个很好的通用答案。您还可以使用 java.nio.ByteBuffer 执行相同的操作,这会导致代码稍微少一些,并且您还可以控制输出的字节顺序(字节顺序)。

创建字节数组:

public static byte[] toByteArray(int bits) {
    ByteBuffer buf = ByteBuffer.allocate(4);
    buf.putInt(bits);
    return buf.array();
}

反转它:

public static int fromByteArray(byte[] b) {
    ByteBuffer buf = ByteBuffer.wrap(b);
    return buf.getInt();
}

Björn gave a good generic answer with using streams. You can also do this same thing using java.nio.ByteBuffer which results in slightly less code and you could also control endianess (byte order) of the output.

To create the byte array:

public static byte[] toByteArray(int bits) {
    ByteBuffer buf = ByteBuffer.allocate(4);
    buf.putInt(bits);
    return buf.array();
}

To reverse it:

public static int fromByteArray(byte[] b) {
    ByteBuffer buf = ByteBuffer.wrap(b);
    return buf.getInt();
}
零度° 2024-09-08 20:14:13

我的第一个答案是位移,但转念一想,我认为使用输出流可能更好、更容易理解。我通常会避免强制转换,但如果您不寻求通用解决方案,我想那也没关系。 :)

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

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

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

And to reverse it:

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();
}
心凉怎暖 2024-09-08 20:14:13

你必须转换为(byte),因为java中默认的数字类型是int,它比byte大。只要该值适合字节就可以进行转换。

You have to cast to (byte) as default number type in java is int, which is bigger than byte. As long as the value fits in byte it is ok to cast.

傲世九天 2024-09-08 20:14:13

试试这个:

sendData[0] =(byte)0x26
sendData[1] =(byte)0x94

或者这个:

sendData[0] =(byte)38
sendData[1] =(byte)148

您必须将数据转换为字节才能将其分配给字节!

这并不意味着你失去了精度,仅仅写 0x26 就意味着 Java 编译器的 int 。

但还要注意:字节的范围是从 -128 到 127,所以在 0x94= 的情况下148 字节转换后它将表示为 '-108' ,因此它在数学计算中将无法正常工作。

Try this:

sendData[0] =(byte)0x26
sendData[1] =(byte)0x94

Or this:

sendData[0] =(byte)38
sendData[1] =(byte)148

You must cast data into byte in order to assign it to a byte!

That does not mean you lost precision, just writing 0x26 means an int to Java compiler..

But also note: range of a byte is from -128 to 127, so in case of 0x94=148 it will be represented after byte casting as '-108' , so it will not work correctly in mathematical computations..

拒绝两难 2024-09-08 20:14:13

这是因为 Java 中的所有内容都是有签名的。 0x94 (148) 大于 Byte.MAX_VALUE(2^7-1)。

你需要的是

public static byte[] intToByteArray(int value) {
    byte[] b = new byte[4];
    for (int i = 0; i < 4; i++) {
        int offset = (b.length - 1 - i) * 8;
        b[i] = (byte) ((value >>> offset) & 0xFF);
    }
    return b;
}

It's because everything in Java is signed. 0x94 (148) is greater than Byte.MAX_VALUE(2^7-1).

What you need is

public static byte[] intToByteArray(int value) {
    byte[] b = new byte[4];
    for (int i = 0; i < 4; i++) {
        int offset = (b.length - 1 - i) * 8;
        b[i] = (byte) ((value >>> offset) & 0xFF);
    }
    return b;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文