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. How to se开发者_JS百科nd an integer higher than 256 in a pack(C*)
or byte[][]
?
$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.
This is the java code from MousePressed on swing (I want to send to the server the current click)
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. Therefore, if you want to extract an integer from a length-4 byte array, you need to do something like
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
You can send 32-bit ints in the following manner.
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.
精彩评论