Search code examples
javac#byteunsignedsigned

C# to Java Byte Conversion


I'm attempting to build a TCP Client in C# that passes over files (mainly MP3) over to an Android application, but I'm having great difficulty converting between unsigned and signed bytes.

What am I doing wrong to get the mismatch in values retrieved by the app?

The below is the data C# is sending across via TCP.

new byte[] { 9, 1, 251, 252, 253, 254, 255, 254, 253, 252, 251, }

Java

while ((charsRead = in.read(buffer)) != -1)
{
    serverMessage = new String(buffer).substring(0, charsRead);
    serverByteMessage = serverMessage.getBytes();
    for(int i = 0; i < serverByteMessage.length; i++) {
        int bi = serverByteMessage[i] & 0xFF;
        Log.e("TCP Client", "Item: " + serverByteMessage[i]);
        Log.e("TCP Client", "Value of my test unsigned byte: " + bi);
    }
}

Java Output

Item: 9
Value of my test unsigned byte: 9
Item: 1
Value of my test unsigned byte: 1
Item: -17
Value of my test unsigned byte: 239
Item: -65
Value of my test unsigned byte: 191
Item: -67
Value of my test unsigned byte: 189
Item: -17
Value of my test unsigned byte: 239
Item: -65
Value of my test unsigned byte: 191
Item: -67
Value of my test unsigned byte: 189
Item: -17
Value of my test unsigned byte: 239
Item: -65
Value of my test unsigned byte: 191
Item: -67
Value of my test unsigned byte: 189
Item: -17
Value of my test unsigned byte: 239
Item: -65
Value of my test unsigned byte: 191
Item: -67
Value of my test unsigned byte: 189
Item: -17
Value of my test unsigned byte: 239

Solution

  • When you convert binary to text, you can only convert valid byte encodings to text. If you convert random data to text, any invalid code are typically replaced with a ?

    The simple solution is to avoid mixing text and binary unless you really know what you are doing.

    InputStream in = socket.getInputStream();
    int bytesRead;
    byte[] bytes = new bytes[512];
    while((bytesRead = in.read(bytes)) > 0) {
       for (int i =0; i < bytesread; i++) {
           int bi = bytesRead[i] & 0xFF;
           System.out.println(bi);
       }
    }
    

    Note: You cannot assume that TCP supports messages. It only supports a stream of bytes. Your have to have a protocol which allows you to work out when a message starts/finishes. e.g. you should send the length of the message before the actual message.