Search code examples
javachartype-conversionipstring-conversion

Java can't get right values for vars


I am building a tool which retrieves the server lists from quake 3 engine master servers (cod2 master server in this case). These master servers respond with a big string containing ip port info. The ip in this is 4 chars, which each should translate to a number (1-255). Though when I try these the numbers above 128 translate to this unicode replacement character (65533 or fffd).

I tried a few things:

System.out.println("ip: "+String.format("%02x", (int)r.charAt(i+1))+"."+String.format("%02x", (int)r.charAt(i+2))+"."+String.format("%02x", (int)r.charAt(i+3))+"."+String.format("%02x", (int)r.charAt(i+4)));
System.out.println("ip: "+(int)r.charAt(i+1)+"."+(int)r.charAt(i+2)+"."+(int)r.charAt(i+3)+"."+(int)r.charAt(i+4));

In php this all works with the same strings with the function:

ord(char);

I think the problem might be that my java uses Unicode, and I think it should use ascii (or extended ascii, not sure).

[8n] << these 4 chars translate correct

��zH << here's one which is incorrect, I just can't copy the right symbols from my console, and if I write it to a txt file I get completely different results with each text editor, so ye..

Any solutions?


Solution

  • You can use Byte.toUnsignedInt to convert the bytes to ints directly:

    byte[] bytes = { (byte) 244, 12, 13, (byte) 155 }; // an example input
    
    int[] ip = new int[4];
    for(int i = 0; i < bytes.length; i++) {
        ip[i] = Byte.toUnsignedInt(bytes[i]);
    }
    
    System.out.println(Arrays.toString(bytes)); // [-12, 12, 13, -101]
    System.out.println(Arrays.toString(ip)); // [244, 12, 13, 155]