I need to write this in Java.
我需要用Java编写这个。
Although I know how to read a file, I'm interested in what the 'buff' output is, is the length at the beginning?
虽然我知道如何读取文件,但我对'buff'输出是什么感兴趣,是开头的长度?
char *buff;
unsigned char *aux;
while(fgets (buff+2, length, fin)){
len = strlen (buff + 2) + 2;
aux = (unsigned char *) &len;
buff[1] = aux[0];
buff[0] = aux[1];
...
send (sd, buff, len, 0);
}
but I don't understand this:
但我不明白这个:
aux = (unsigned char *) &len;
buff[1] = aux[0];
buff[0] = aux[1];
Thanks in advance.
提前致谢。
2 个解决方案
#1
0
This code:
aux = (unsigned char *) &len;
buff[1] = aux[0];
buff[0] = aux[1];
creates a byte-array view of the integer value stored in len
. In Java, you can't do exactly the same thing, but you can get what you want a couple of ways. The easiest is just with bit masking and shifting:
创建存储在len中的整数值的字节数组视图。在Java中,你不能完全做同样的事情,但你可以通过几种方式获得你想要的东西。最简单的就是使用位屏蔽和移位:
int len = ...;
byte[] buff = ...;
byte[0] = (byte) (len & 0xff);
byte[1] = (byte) ((len >> 8) & 0xff);
Another possibility is to use a ByteBuffer
, but that seems overkill for such a simple operation.
另一种可能性是使用ByteBuffer,但这对于这样一个简单的操作来说似乎有些过分。
#2
0
buff
appears to be the buffer used to read data from the file. It looks like the program makes the assumption that len
will only be at most two (sizeof(unsigned char)) bytes long. So it packs the lower-most two bytes of len
into buf[1:0]
by parsing the address of len
as an unsigned char *
and thereby grabbing the lower-most two bytes of len
and sticking them into the lower-most two bytes of buff
.
buff似乎是用于从文件中读取数据的缓冲区。看起来该程序假设len最多只有两个(sizeof(unsigned char))字节长。因此,它通过将len的地址解析为unsigned char *来将len的最低两个字节打包到buf [1:0]中,从而获取len的最低两个字节并将它们粘贴到最低的两个字节中浅黄色
#1
0
This code:
aux = (unsigned char *) &len;
buff[1] = aux[0];
buff[0] = aux[1];
creates a byte-array view of the integer value stored in len
. In Java, you can't do exactly the same thing, but you can get what you want a couple of ways. The easiest is just with bit masking and shifting:
创建存储在len中的整数值的字节数组视图。在Java中,你不能完全做同样的事情,但你可以通过几种方式获得你想要的东西。最简单的就是使用位屏蔽和移位:
int len = ...;
byte[] buff = ...;
byte[0] = (byte) (len & 0xff);
byte[1] = (byte) ((len >> 8) & 0xff);
Another possibility is to use a ByteBuffer
, but that seems overkill for such a simple operation.
另一种可能性是使用ByteBuffer,但这对于这样一个简单的操作来说似乎有些过分。
#2
0
buff
appears to be the buffer used to read data from the file. It looks like the program makes the assumption that len
will only be at most two (sizeof(unsigned char)) bytes long. So it packs the lower-most two bytes of len
into buf[1:0]
by parsing the address of len
as an unsigned char *
and thereby grabbing the lower-most two bytes of len
and sticking them into the lower-most two bytes of buff
.
buff似乎是用于从文件中读取数据的缓冲区。看起来该程序假设len最多只有两个(sizeof(unsigned char))字节长。因此,它通过将len的地址解析为unsigned char *来将len的最低两个字节打包到buf [1:0]中,从而获取len的最低两个字节并将它们粘贴到最低的两个字节中浅黄色