don-prog don-prog - 4 months ago 29
Java Question

int to unsigned char array in Java

I'm trying to connect Android(Java) with Linux(Qt C++) using socket. After that I want to transfer length of message in bytes. For converting int in unsigned char array on the C++ side I use:

QByteArray IntToArray(qint32 source)
{
QByteArray tmp;
QDataStream data(&temp, QIODevice::ReadWrite);
data << source;
return tmp;
}


But I don't know how I can do the same converting on the Java side, because Java hasn't unsigned types. I tried to use some examples but always got different results. So, I need Java method which returns this for
source
= 17:

0x00
,
0x00
,
0x00
,
0x11


I understand that it's a very simple question, but I'm new in Java so it's not clear to me.

UPD:

Java:

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.print(ByteBuffer.allocate(4).putInt(17).array());


Qt C++:

QByteArray* buffer = new QByteArray();
buffer->append(socket->readAll());


Output:


buffer
=
0x5b
,
0x42
,
0x40
,
0x61
,
0x39
,
0x65
,
0x31
,
0x62
,
0x66
,
0x35
.


UPD2:

Java:

out.print(toBytes(17));
...
byte[] toBytes(int i)
{
byte[] result = new byte[4];

result[0] = (byte) (i >> 24);
result[1] = (byte) (i >> 16);
result[2] = (byte) (i >> 8);
result[3] = (byte) (i /*>> 0*/);

return result;
}


Qt C++: same

Output:


buffer
=
0x5b
,
0x42
,
0x40
,
0x63
,
0x38
,
0x61
,
0x39
,
0x33
,
0x38
,
0x33
.


UPD3:

Qt C++:

QByteArray buffer = socket->readAll();
for(int i = 0; i < buffer.length(); ++i){
std::cout << buffer[i];
}
std::cout<<std::endl;


Output:


[B@938a15c

Answer

First of all, don't use PrintWriter.

Here's something to remember about Java I/O:

  • Streams are for bytes, Readers/Writers are for characters.
  • In Java, a character is not a byte. Characters have an encoding associated with them, like UTF-8. Bytes don't.

When you wrap a Stream in a Reader or a Writer, you are taking a byte stream and imposing a character encoding on that byte stream. You don't want that here.

Just try this:

    OutputStream out = socket.getOutputStream();
    out.write(toBytes(17));
Comments