Delphi-determine the number of 1 in a binary number

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.