Technical Exchange and DH explanation
A friend sent a text message for help. I think he was writing a test. Haha. c ++, but after we know the principle, everything is the same.
The binary form of A number is like this.
10011001. If we need to determine the number of 1, we only need
00000001 and, and then shift right.
For example, the first time:
10011001 and 00000001 = 1 indicates that this digit is 1
01001100 and 00000001 = 0 indicates that this digit is not 1
Move to the right
00100110 and 00000001 = 0. This is not 1.
Let's take a look at Delphi. Code :
Program Project2;
{$ Apptype console}
Uses
Sysutils;
VaR
I, N, C: integer;
Begin
{Todo-ouser-cconsole main: insert code here}
C: = 9999;
N: = 0;
For I: = 0
To 32-1
Do
Begin
If C
And 1 = 1
Then
INC (N );
C: = C
SHR 1;
End ;
Writeln (N );
Readln (N );
End .
Judge the number of 1 in 9999. Because we use integer and 32-bit signed integer, we shifted it to 32 times.
Do you understand?
Write a program in Embedded Assembly later.
Wait until the exam is over.
Function Get1digital (N: integer): integer;
ASM
// Number of cycles
MoV ECx, 32
// Save one count
XOR EdX, EDX
Push EBX
@ Nloop:
// Save the eax Value
MoV EBX, eax
// Perform operations on eax and 1
And Eax, 1
// Skip if eax is 0
JZ @ nd
// Add 1
INC edX
@ Nd:
MoV eax, EBX
// Shift one digit to the right
SHR Eax, 1
// Reduce the number of cycles by one
Dec ECx
// Loop
Jnz @ nloop
Pop EBX
// Return results
MoV eax, EDX
End ;
// Compilation is still very simple. I haven't written Delphi code for a long time.
It seems that you have not considered a signed integer. Haha. Sin.
Okay. I'm DH.