ChristianNRW
ChristianNRW

Reputation: 542

php Values Java Byte Array

I am a bit confiused about the "pack" / "unpack" php Function, so i need the php Equivalent to the following Java Code

....
byte[] TempByte = {1, (byte)0x01};
...

php:

?

thx

Upvotes: 0

Views: 1713

Answers (3)

linski
linski

Reputation: 5094

The code you posted initializes a byte array consisting of two elements, bytes.

Since PHP is weakly typed you cannot get an exact equivalent of this code - which can be seen from the list of PHP types.

Both languages have arrays, so we re good here, but PHP doesn't have byte.

In Java a byte is defined as an signed 8-bit value ranging from -128 to 127 (inclusive).

The closest thing to that PHP would be an integer, but:

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

So, my suggestion would be (for a 32bit platform):

$TempByte = array(0x0001 & 1, 0x0001 & 1);

Upvotes: 1

deceze
deceze

Reputation: 522342

I'm not 100% sure what that Java code does, but it looks equivalent to something like this:

$tempByte = "\x01\x01";

"Byte arrays" are essentially strings in PHP, or rather "strings" are essentially byte arrays in PHP. You can even access this "byte array" using the array offset syntax:

echo bin2hex($tempByte[0]);

Upvotes: 1

JvdBerg
JvdBerg

Reputation: 21856

There is no real php equivalent, as php is loosely typed, and not has a byte[] type.

The code that resembles your java code most is:

$TempByte = array(1, chr(1));

Upvotes: 2

Related Questions