I thought it might be byte ordering but it doesn't look like it. I am not sure what else it could be.
private static final int CODE = 0;
Socket socket = new Socket("10.10.10.10", 50505);
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.writeInt(CODE);
int sd = createSocket();
int code = -1;
int bytesRead = 0;
int result;
while (bytesRead < sizeof(int))
{
result = read(sd, &code + bytesRead, sizeof(int) - bytesRead);
bytesRead += result;
}
int ntolCode = ntohl(code); //test for byte order issue
printf("\n%i\n%i\n%i\n", code, ntolCode, bytesRead);
Which prints out:
-256
16777215
4
Not sure what else to try.
This solution is not intuitive in the least for me, but thanks for the down votes anyway!
Socket socket = new Socket("10.10.10.10", 50505);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
int x = 123456;
ByteBuffer buff = ByteBuffer.allocate(4);
byte[] b = buff.order(ByteOrder.LITTLE_ENDIAN).putInt(x).array();
out.write(b);
int sd = createSocket();
char buff[4];
int bytesRead = 0;
int result;
while (bytesRead < 4){
result = read(sd, buff + bytesRead, sizeof(buff) - bytesRead);
if (result < 1) {
return -1;
}
bytesRead += result;
}
int answer = (buff[3] << 24 | buff[2] << 16 | buff[1] << 8 | buff[0]);
I am still interested in a simpler solution if anyone has anything, preferably using BufferedWriter if that is possible.
The problem is here:
&code + bytesRead
This will increment the address of code
in steps of 4 (sizeof code
), not 1. You need a byte array, or some typecasting.