


Interview question: Explanation of the implementation idea of reversing binary bits (PHP general version)
This is an interview question, and some students expressed that they could not understand it. It is not difficult to give you a simple training, but to write a perfect comparison tests the basic skills, and also requires some logical thinking ability. Since the students' direction is PHP, then I will use PHP to explain it. At the same time, it also tells everyone that learning PHP is not It is said that as long as you can write two sentences of echo "hello world", or loop output to a web page, you can call PHP.
Here are a few pieces of knowledge: (Recommended learning: PHP video tutorial)
##1 , a number occupies one byte, that is, 8 bits
For example, the decimal number 1 is expressed in binary on the computer as 00000001 (If you forget to convert decimal to binary, please Baidu, this Forget that you can’t understand the following~~~) You can useecho bindec("00000001"); //bindec函数可以让你体会到 二进制和10进制之间的 骚转换<br/>
#2 in PHP. Add decimal numbers 1 1 =2 (This tip is very important~~, Carefully understand)
Use binary to do it with displacementAnswer: 00000010 This is exactly 2 (2 raised to the power of 1)
Answer: 00000011 This is exactly 3 (2 to the power of 1 2 to the power of 0 = 2 1 = 3)
Answer: 00000100 This is 4 (2 to the power of 2)
Answer: 00000101 This guy is 4 (2 to the power of 2, 2 to the power of 0 = 4 1 = 5)
Start to solve the problem
Suppose there is a binary number 00000101. Now we need to turn it upside down and turn it into 10100000. How to play? The answers are all over the Internet, so let’s talk about the ideas below:1. First, there must be 2 variables,
1 ) The temporary variable is called $xxoo, and the initial value is 0 (decimal), which is 00000000 in binary. 2) The original value variable is called $shit, which is 00000101 to be processed2. 3 steps
1) Move $xxoo one bit to the left 2) Determine whether the last digit of the binary value of $shit is 1. If so, give $ The decimal value of xxoo is increased by 1. It is very important to regard it as binary and change 00000000 into 00000001. Otherwise, the initial value of $xxoo is 00000000. This is shifted by p. . . They are all zero, so how to determine whether the last bit of the binary number is 1? You have to judge by intercepting strings or regular expressions (not impossible)Answer: Just perform a logical AND operation on the original value and 1 (that is, 00000001) (1&1 is 1, 1&0 or 0&1 are always 0)
3) Next, move $shit to the right by 1 position
1) If it was originally 00000101, it becomes 00000010 after the move ( That is to say, $xxoo and shit are moved at the same time, one to the left and one to the right. When the last bit of shit is 1, we can judge it, so the last bit of $xxoo is also set to 1, so that both xxoo and shit can be realized. Synchronization and reverse) Repeat the above process 8 times to get 10100000 The complete code is as followsfunction rev($n)<br/>{<br/> $xxoo = 0;<br/> for ($i = 0; $i < 8; $i++) {<br/> $xxoo = $xxoo << 1;<br/> if (($n & 1) == 1) {<br/> $xxoo++;<br/> }<br/> $n = $n >> 1;<br/> }<br/> return $xxoo;<br/>}<br/>echo decbin(rev(5));<br/>
But be careful The thing is, the above function supports 1-byte numbers (only supports 8 digits)
The online interview questions are 32-bit numbers, and the following code supportsgeneral digits (this code is not available online~~~). Let’s think about it and understand it, so I won’t explain too much. You need to have some PHP code skills:
function rev($n)<br/>{<br/> $num=intval(strlen(decbin($n))/8); //整除 8<br/> if($num==0)<br/> $bitLen=8;//最小8位<br/> else<br/> {<br/> if((strlen(decbin($n)) % 8)>0)<br/> $bitLen=($num+1)*8;<br/> else<br/> $bitLen=$num*8;<br/> }<br/> echo “原始值二进制:”.str_pad(decbin($n),$bitLen,’0′,STR_PAD_LEFT).”<br/>”;<br/> $xxoo = 0;<br/> for ($i = 0; $i < $bitLen; $i++) {<br/> $xxoo = $xxoo << 1;<br/> if (($n & 1) == 1) {<br/> $xxoo++;<br/> }<br/> $n = $n >> 1;<br/> }<br/> echo “反转后值二进制:”.str_pad(decbin($xxoo),$bitLen,’0′,STR_PAD_LEFT).”<br/>”;<br/> return $xxoo;<br/>}<br/>
Call testecho rev(4);<br/>echo rev(43261596);<br/>
Result原始值二进制:00000100<br/>反转后值二进制:00100000<br/>32原始值二进制:00000010100101000001111010011100<br/>反转后值二进制:00111001011110000010100101000000<br/>964176192<br/>
The above is the detailed content of Interview question: Explanation of the implementation idea of reversing binary bits (PHP general version). For more information, please follow other related articles on the PHP Chinese website!

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor
