[英]Byte Operations and Datagrams in Java
I am trying to program a handshake type message as follows where C=Client S=Server: 我正在尝试编写一个握手类型的消息,如下所示,其中C = Client S = Server:
C-->S: "I'd like to talk" //session initiation
S-->C: "80" //(n, randomly generated number)
C-->S: "81" //(n+1)
S: "does n= (n+1)-1?" //confirms the connection.
For the purposes of this question assume that the logic above is correct. 出于这个问题的目的,假设上面的逻辑是正确的。 I would like the random number I generated to be a 32 bit number (ie 4 bytes sent in a UDP datagram).
我希望我生成的随机数是32位数(即UDP数据报中发送的4个字节)。 Since an int is 32 bits, I would prefer to use this data type, but I seem to run into one of two problems:
由于int是32位,我更喜欢使用这种数据类型,但我似乎遇到了两个问题之一:
I found a method that can convert from an int to bytes. 我找到了一个可以从int转换为字节的方法。 I found some information regarding using a Bytebuffer to convert to an int, but I'm not sure it's even correct.
我找到了一些关于使用Bytebuffer转换为int的信息,但我不确定它是否正确。 Is there an easier way to go about a process of sending an int in a datagram?
有没有更简单的方法来处理在数据报中发送int的过程? It seems like an extraordinary amount of work to keep converting back and forth between bytes and ints.
在字节和整数之间来回转换似乎是一项非常大的工作。
Nothing hard about any of those operations. 任何这些操作都没什么难的。
DataInputStream
and DataOutputStream
take care of the stream->int->stream
conversions, and ByteArrayInputStream
and ByteArrayOutputStream
take care of the stream->byte[]->stream
conversions. DataInputStream
和DataOutputStream
负责stream->int->stream
转换, ByteArrayInputStream
和ByteArrayOutputStream
负责stream->byte[]->stream
转换。
There are two options: 有两种选择:
converting via bitshift: 通过bitshift转换:
//int to byte[] int val = someval; byte[] bytes = new byte[4]; for(int i = 0 ; i < 4 ; i++) bytes[i] = (byte) (val >>> (i * 8)); //byte[] to int int val = 0; byte[] bytes = input(); for(int i = 0 ; i < 4 ; i++) val |= ((int)(bytes[i])) << i * 8;
If you are defining your own format of the datagram, it's easy enough to establish that the nth 4 bytes of content represent an integer. 如果要定义自己的数据报格式,则很容易确定内容的第n个4字节表示整数。
You then can use some simple conversion functions to go from int
to byte[]
and vice-versa. 然后,您可以使用一些简单的转换函数从
int
到byte[]
,反之亦然。
A small class implementing this two methods should do: 实现这两种方法的小类应该:
public static byte[] toByteArray(int value) {
byte[] b = new byte[4];
// MSB to LSB
b[0] = (byte) (value >> 24);
b[1] = (byte) (value >> 16);
b[2] = (byte) (value >> 8);
b[3] = (byte) (value);
return b;
}
public static int fromByteArray(byte[] value) {
int i = ((((int) value[0]) & 0xFF) << 24) |
((((int) value[1]) & 0xFF) << 16) |
((((int) value[2]) & 0xFF) << 8) |
((((int) value[3] & 0xFF)));
return i;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.