I found this snippet of code online and I was wondering what it does:
$k[$i] = ord($key{$i}) & 0x1F;
I know that ord()
returns an ASCII value, but I'm unclear on what the curly brackets do $key{$i}
and also what this does & 0x1F
.
I found this snippet of code online and I was wondering what it does:
$k[$i] = ord($key{$i}) & 0x1F;
I know that ord()
returns an ASCII value, but I'm unclear on what the curly brackets do $key{$i}
and also what this does & 0x1F
.
That's not an array syntax. It's for accessing single characters from strings only. The index must be numeric.
$str{1} == $str[1]
It's briefly mentioned here in the info box: http://www.php.net/manual/en/language.types.string.php#language.types.string.substr
Also, it's officially declared deprecated. It has been on and off supposed deprecation in the manual, but is still very valid, if uncommon, syntax.
The & 0x1F
is a bit-wise AND. In this case it limits the decimal values to 0 till 31.
In PHP, either [square brackets] or {curly braces} are fully legal, interchangeable means of accessing an array:
Note: Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above).
Source: http://www.php.net/manual/en/language.types.array.php
Both are fully valid; curly braces are not deprecated.
Concerning "& 0x1F", others like @Tadek have responded:
& is a binary operator. See more in the documentation [http://www.php.net/manual/en/language.operators.bitwise.php]. It sets the bits if they are set in both variables.
First part of your question: curly braces
This is about referencing the value of the variable.
In your example, if $i
is equal to 123
, then
$k[$i] = ord($key{$i}) & 0x1F;
will be the same as
$k[123] = ord($key[123]) & 0x1F;
Second part of your question: '&' sign
&
is a binary operator. See more in the documentation. It sets the bits if they are set in both variables.
The & 0x1F
is a bit-wise operation, used to "normalize" values of characters, colors, etc, that are put into hex but aren't necessarily "read" the same. Read more on Wikipedia here.
& 0x1f
is equivalent to
& 00011111
This can effective set the first three bits of any byte-sized value to 0.
0xff & 0x1f
results in
0x1f
or
11111111 & 00011111
results in
00011111