Editing
PHP Skills Tests
(section)
Jump to navigation
Jump to search
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Bit shifting === '''Q: What will be the output of the following code?''' <syntaxhighlight lang="php"> $a = 0x01; // 1 $b = 0x02; // 2 echo $a === $b >> $a; </syntaxhighlight> {| | '''a.''' | 0 |- | '''b.''' | 1 |- | '''c.''' | Syntax error |} '''A: (b) 1''' * `$a` equals 1 * `$b >> $a` shifts the bit in 2 over one place, resulting in 1 * `$a === $b >> $a` translates to "does 1 equal 1?" * Answer is "yes", i.e. true, i.e. 1 ---- '''Q: What will be the result of the following code?''' <syntaxhighlight lang="php"> $a = 0x01; // 1 $b = 0x02; // 2 printf("%x", ($a << $b.$b)); // 400000 </syntaxhighlight> * `%x` format for `printf()` means output a hexidecimal value using lowercase letters. * `$b.$b` evaluates to `22`. * So, shift a bit representing 1 over 22 places, i.e. 2 to the power of 22. * When you shift the bit over, you multiply the value by 2, so the progression is like 1, 2, 4, 8, and then `8 * 2 = 16` which in hex is 10. Then `10 * 2` in hex results in 20 which is really `16 * 2` or `2**5` or `32`. * An algorithm for translating the shift to hex would be `(2**($shift_value % 4)) . str_pad(<nowiki>''</nowiki>, floor($shift_value/4), '0')` ---- '''Q: What will be the output of the following code?''' <syntaxhighlight lang="php"> $a = (1<<0); // 0b0001, or 1 $b = (1<<1); // 0b0010, or 2 echo ($b|$a) << 2; </syntaxhighlight> {| ! a. | 1 |- ! b. | 2 |- ! c. | 3 |- ! d. | 4 |- ! e. | 8 |- ! f. | 12 |- ! g. | Syntax error |} '''A: (f) 12''' * `($b|$a)` Or operator set the bit if it's set in either `$b` or `$a`, or `0b0010 | 0b0001` = `0b0011`, or `3` * Shift 3 two places yields `0b1100` or `12` * Also, shifting a bit left in effect multiplies the value by 2 for each time the bit is shifted, so `3 * 2 * 2 = 12` * Also, shifting a bit left if effect multiplies the value by 2 to the power of the shift amount, e.g. `3 * (2**2) = 3 * 4 = 12`
Summary:
Please note that all contributions to Littledamien Wiki may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Littledamien Wiki:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Navigation menu
Personal tools
Not logged in
Talk
Contributions
Create account
Log in
Namespaces
Page
Discussion
English
Views
Read
Edit
View history
More
Search
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Tools
What links here
Related changes
Special pages
Page information