我有一个要求,通过套接字,即winsock接口(interface),从用C编写的 native 程序发送数据。然后该数据由 Java 程序接收。 Java 程序接收一个它知道顺序的数据包并进行一些处理。它采用从 socket.Read() 接收的 int,如 client_socket.getInputStream().read()
解析从 Read() 返回的 int 数据的处理以获得预期的数据类型。基本上它是接收到的大量数据的切片。我只能假设 read() 函数一次读取 4 个字节(32 位 java int 大小)。所以我继续将这 4 个字节(8 位不是 Java 类型)分成 4 个 Java 短裤,这样我就可以正确地表示它们所代表的无符号值。 在我有 4 条短裤之后,如果我知道我想要一个 uint16,我只需连接 2 条短裤
问题是我在某个地方做了一些错误的位操作,结果没有像我想象的那样工作。 下面是 C 代码和 Java 代码,虽然它不起作用,但它非常简单。输出是我无法理解的原因。
0 0 0 0 0 1 0 0 0 2 0 0 0 3 0 0 0 4 {...}
C 代码编辑了初始化部分:
uint16_t buffer[255] = {};
uint16_t *current_pointer = buffer;
for(uint16_t index = 0; index < 255; index++) {
*current_pointer = index;
current_pointer++;
}
Write(client_socket, (char *)buffer, sizeof(buffer));
Java 代码也经过编辑:
public final short[] JavaIntToUint8Array(int unsigned_int) {
return new short[] { (short)((unsigned_int & 0xFF000000L) >> 24),
(short)((unsigned_int & 0x00FF0000L) >> 16),
(short)((unsigned_int & 0x0000FF00L) >> 8),
(short)((unsigned_int & 0x000000FFL))};
}
public final int[] JavaIntToUint16(int unsigned_int) {
short uint8_array[] = JavaIntToUint8Array(unsigned_int);
return new int[] { (int)(uint8_array[0] << 8) | (int)uint8_array[1],
(int)(uint8_array[2] << 8) | (int)(uint8_array[3]) };
}
...
while (index < 255) {
read_data = data_input.read();
System.out.print(" ");
System.out.print(JavaIntToUint16(read_data)[0]);
System.out.print(" ");
System.out.print(JavaIntToUint16(read_data)[1]);
System.out.print("\t");
index++;
}
最佳答案
I can only assume that the read() functions reads 4 bytes at a time (the 32 bit java int size)
不,你不能这样假设。 documentation for InputStream.read()
说:
public abstract int read() throws IOException
Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
A subclass must provide an implementation of this method. Returns: the next byte of data, or -1 if the end of the stream is reached.
关于java - 将 uintN 数据类型从 C 传输到 Java(套接字编程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7866373/