简体   繁体   English

通过Perl和Java套接字的Byte数组中的值错误

[英]Wrong value in Byte array through Perl and Java socket

Perl
x=1
y=222

java
x=257
y=222

I understand that I can only put an integer between 0 and 256 in a byte. 我了解我只能将0到256之间的整数放在一个字节中。 How to send an integer higher than 256 in a pack(C*) or byte[][] ? 如何在pack(C*)byte[][]发送大于256的整数?

$data = $n->read($data2, 6);
@arr =  unpack("C*", $data2);

Sometimes when I send a value from Perl to Java, I catch a negative value in Java side, the issue is that I want to keep byte array only. 有时,当我从Perl向Java发送值时,我在Java端遇到了一个负值,问题是我只想保留字节数组。

This is the java code from MousePressed on swing (I want to send to the server the current click) 这是挥杆时MousePressed的Java代码(我想将当前点击发送到服务器)


public void mousePressed(MouseEvent e) {
        Point p = e.getPoint();
        byte[] buff = new byte[]{02,00,(byte)p.x,(byte)p.y,00,00};
                //write buff on my socket

Thanks 谢谢

Java bytes are signed and they will hold their sign when you try to convert back to an integer. Java字节是带符号的,当您尝试转换回整数时,它们将保留其符号。 Therefore, if you want to extract an integer from a length-4 byte array, you need to do something like 因此,如果要从长度为4的字节数组中提取整数,则需要执行以下操作

int num = 0;
for(int i=0;i<4;i++){
    num <<= 8;
    num |= byteArray[i] & 255;
}
return num;

If you leave out the "& 255", you probably won't get the number you were expecting 如果省略“&255”,则可能无法获得预期的数字

You can send 32-bit ints in the following manner. 您可以通过以下方式发送32位整数。

DataOutputStream dos = ...
dos.writeByte(2);
dos.writeByte(0);
dos.writeInt(p.x);
dos.writeInt(p.y);
dos.writeByte(0);
dos.writeByte(0);
dos.flush(); // assuming you use buffering.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM