Search code examples
javaphppack

PHP's pack("N", $str) in Java


I need help with translating this line of PHP into Java pack( 'N', $data )

$data should be 7-9 numeric characters, the last being null

I guess it would be packed into a long after going through that function.

which will be pushed through a socket into a server which will run this:

byte[] abyte = datagrampacket.getData();
c(abyte, 7, datagrampacket.getLength())

and c(...) is the following:

public static int c(byte[] abyte, int i, int j) {
    return 0 > j - i - 4 ? 0 : abyte[i] << 24 | (abyte[i + 1] & 255) << 16 | (abyte[i + 2] & 255) << 8 | abyte[i + 3] & 255;
}

I guess the function above just expands it back into the original $data

Anyone have any ideas how I "pack" it in java?

EDIT: what it does to the data through php:

Stripped Received Data:
array
  0 => string '13231786�' (length=9)
  1 => string '/31/33/32/33/31/37/38/36/0' (length=26) <--- dechex(ord()) for each char above
Packed Data:
array
  0 => string '�Éæª' (length=4)
  1 => string '/0/c9/e6/aa' (length=11) <--- dechex(ord()) for each char above

Solution

  • After a day of working at this mathematically, I've figured it out. It's actually pretty simple now that I've figured it out.

    in java:

    int x = (int) Math.floor(j/2^16);
    int y = (int) Math.floor((j-(x*65536))/2^8);
    int z = (int) Math.floor(j-((x*2^16)+(y*2^8)));
    
    x = 2nd character
    y = 3rd character
    z = 4th character
    

    these numbers are in triple digits so you'd need to convert it to hexadecimal. Just for reference for anyone who happens to stumble upon this exact problem.