Preface
There is an integer, and you want to know that there are multiple 1s in its binary representation. What would you do? This article will take you in-depth study of binary and its various operations, step by step to study the solution to this problem, and all interested developers are welcome to read this article.
Pre-knowledge
Before solving this problem, we need to understand what is binary.
Binary
In the computer world, there are only 0 and 1, which is binary.
Number of symbols
In binary, the number is divided into signed number and unsigned number .
For signed numbers, , the positive and negative signs of the machine cannot be recognized, but because "positive and negative" happen to be two completely different states, if you use "0" for positive and "1" for " "Negative", so that the symbol is also digitized, and it is stipulated that it is placed in front of the effective number, which constitutes a signed number.
Therefore, the highest bit is used to represent the sign in binary.
- The highest bit is 0, which means a positive number.
- The highest bit is 1, which means a negative number.
The highest bit of the binary is its first bit, for example: 10000001100, its highest bit is 1.
For unsigned numbers, , the range of the number it represents is a positive number, and all bits are used to represent the size of the number.
Properties of signed numbers
For signed numbers, it has 6 properties:
- The highest bit of the binary is the sign bit: 0 means positive number, 1 means negative number
- The original code, one's complement, and the complement of a positive number are the same
- The inverse code of a negative number = the sign bit of the original code remains unchanged, and the other bits are inverted (0 -> 1; 1 -> 0)
- The complement and complement of 0 are both 0
- The complement of a negative number = its complement + 1
- In computer calculations, they are all calculated in the way of complements.
Original code, inverse code, complement
In the above properties, we mentioned the original code, the inverse code, and the complement. Next, let's learn what kind of numbers they are.
Original code, divided into two situations:
- A positive number, converted into a binary number according to the absolute value
- A negative number, converted into a binary number according to the absolute value, and then the highest bit is complemented by 1
The inverse code is also divided into two situations:
- A positive number, its inverse code is the same as its original code
- A negative number, its inverse code is the original code of the number except for the sign bit, each bit is inverted
Complement code is also divided into two cases:
- A positive number, its complement is the same as its original code
- A negative number, its complement is to add 1 to the last digit after the original code of the number except the sign bit is inverted.
Base conversion
To perform operations on binary, we need to convert decimal numbers to binary, so we need to learn the method of converting decimal to binary.
Decimal to Binary
Converting decimal to binary is mainly divided into three situations:
- Positive integer to binary
The calculation rule is: Divide by two and take the remainder (until the quotient is 0), then arrange in reverse order, and fill in the high bits with zeros.
After knowing the rules, let's take an example to find the binary number corresponding to 80, as shown in the following figure:
The byte unit of the internal representation of the computer is a fixed length (word length), such as 8, 16, 32, 64 bits. Therefore, when the calculated binary digits are not enough, 0 needs to be added to the high digits.
In the above example, after we convert 80 to a binary number, its value is: 1010000, and the word length is 7. If the word length of the computer is 64 bits, then the standard way of writing is to add 57 zeros in front of its highest bit. We Use a calculator to verify, as shown below:
- Negative integer to binary
In the computer, negative numbers are expressed in the form of the complement of the original code. Through the previous study, we know that we want to find the complement of a negative number, and we have to find the original code first.
We take -80
as an example to calculate its binary code, the steps are as follows:
- Find the original code, as shown in the figure below:
- Find the complement code, as shown in the figure below:
At this point, we got -80
binary code: 10110000
In the part of converting positive integers to binary, we talked about computers with fixed word lengths. When the calculated number of binary digits is not enough, positive integers will be filled with 0 in the high digits, and negative integers will be filled with 1 in the high digits.
We use a calculator to verify whether the binary code of -80 we calculated is correct, as shown below:
- Decimal to binary
In binary, decimals are called floating-point numbers. When we convert decimal decimals to binary decimals, we need to divide them into integer parts and decimal parts when we convert decimal decimals to binary decimals.
The integer part is converted to binary, we have already talked about it before (that is, divide by 2 and take the remainder)
The method to convert the decimal part to binary is: multiply by 2 to take the integer part, and continue to multiply the decimal part by 2 until the decimal part is 0 (in most cases, it will not be 0, and the precision needs to be established)
We take 80.13
as an example to calculate its binary code, as shown in the figure below:
When a computer uses binary to represent decimals, most decimal decimals cannot be accurately represented in binary. When representing such decimals, the maximum precision depends on the computer's word length .
Figure above, we calculated the
80.13
binary code01010000.00100
, we accurate to five decimal places.We use a calculator to verify the correctness.
Binary to decimal
Similarly, binary conversion to decimal is also divided into three situations:
- Positive integer to decimal
Starting from the lowest bit of the binary, label each bit with a serial number, take out the serial number of the number that is not 0, calculate it as a power of 2, and finally add the result.
Let's take 01010000
as an example, find its decimal number, as shown in the figure below:
- Negative integer to decimal
Earlier we learned the method of converting negative decimal integers to binary, then the conversion from binary to decimal needs to be calculated backwards. Let’s take 10110000
as an example. The steps are as follows:
- Find the original code based on the complement
- Remove the sign bit, calculate the other bits according to the rule of converting positive integers to binary, and finally add a negative sign, as shown in the following figure:
- Decimal to decimal
Mark each digit after the decimal point with a negative serial number (starting from -1), take the serial number of the number that is not 0, calculate it as a power of 2, and finally add the result.
Let's take 01010000.00100
as an example to find its decimal number, as shown in the figure below:
After the previous study, we know that when the decimal is converted to binary, the exact value cannot be obtained in most cases. When we use 80.13 as an example, it is accurate to 5 digits after the decimal point.
Similarly, when we convert a binary decimal number to a decimal number, we cannot get the exact value. The final value also depends on the precision. Here we keep 2 decimal places, and after rounding up, it
80.13
.
Signed operations
Complete understanding of pre-knowledge, let's look at a few examples have signed is how the operation.
Left shift operator
<<
called the left shift operator, and its operation rules are:
- Remove the highest 0 of the binary number
- Add a 0 to the end of the binary number
Let's take 01010000
as an example. Assuming that its word length is 32 bits (the extra 0 is omitted), it is shifted to the left by one bit. Its calculation process is shown in the following figure:
010100000
1 bit to the left, the result we calculated is 0617f513c2142b, and the result after conversion to decimal is 2^5 + 2^7 = 32 + 128 = 160
.
01010000
decimal number is 80
, after moving left one, the value becomes 160
, after we found out that the value of the left exactly 2 times of the original value, equivalent to 2 multiply operation.
In most cases, we can use it as a multiplication by 2, but in some special cases it does not represent a real multiplication by 2, for example, we need to shift it to the left by 25 bits, as shown in the figure below (we put the omitted 0 Fill):
After shifting to the left by 25 digits, we find that the 0 on its left has been deleted, and the highest bit has become 1, and this number has also changed from a positive number to a negative number. If we shift to the left by 26 bits, and the 0 on the left is not enough, we will start to take the value from the right, and the final value will become a positive number again.
Therefore, we will find such a rule:
- When the number of bits shifted to the left exceeds the remaining word length, its value is not multiplied by 2.
Note: If any binary number, the number of bits shifted to the left is greater than or equal to the word length (for example, the word length is 32, we shift 32 bits to the left, and 32 zeros on the right), then the corresponding decimal numbers are all 0 ?
Of course not. When a binary number is shifted to the left, when the number of digits moved is greater than or equal to its word length, the number of digits will first find the remainder, and then move to the left.
For example: we need to shift a binary number with a word length of 32 bits to the left by 32 bits, then we need to find its remainder first, that is:
32 % 32 = 0
, which needs to be shifted by 0 bits to the left. The value of shifting 33 bits to the left is the same as shifting 1 bit to the left.
Right shift operator
>>
called the right shift operator, and its operation rules are divided into two cases, positive and negative.
positive number:
Remove the lowest digit and add 0 to the highest digit.
Let's take 01010000
as an example (the decimal value is 80) and shift it right by 4 bits. The calculation process is shown in the figure below:
The calculated binary result is
00101
, convert it to decimal, the result is:2^0 + 2^2 = 1 + 4 = 5
, that is:80 >> 4 = 5
We use a calculator to verify:
negative number :
After the previous study, we know that the negative number is stored in the form of the complement of the original code, and its right shift rule is:
- Shift the complement to the right, and add 1 at the highest bit
- Find the one's complement
- +1 to the inverse code, find the original code
Let's take 10110000
as an example (the decimal system is -80
) and shift it to the right by 4 digits. The calculation process is as follows:
The calculated binary result is
11100
, and we specialize it as a decimal:2^0 + 2^2 = 1 + 4 = 5
, and fill in the sign bit, the result is:-5
. That is:-80 >> 4 = -1
.We use a calculator to verify, as shown in the figure below:
And operator
&
called the AND operator, and its operation rules are:
- The numbers on the left and right sides of the symbol are 1 at the same time, the result is 1, otherwise it is 0
That is: 0 & 0 = 0; 0 & 1 = 0; 1 & 0 = 0; 1 & 1 = 1
Next, look at an example of decimal system and see its arithmetic process, as shown below:
15 & 13
, its operation steps are:
- Convert decimal to binary
- AND operation on binary
The calculation process is shown in the figure below:
Or operator
|
called the OR operator, and its operating rules are:
- One of the numbers on the left and right sides of the symbol is 1, and its value is 1.
That is: 0 | 1 = 1; 1 | 0 = 1; 0 | 0 = 0; 1 | 1 = 1
Let's continue with the numbers in the previous chapter as an example, and look at the calculation steps 15 | 13
- Convert decimal to binary
- OR operation on binary
The calculation process is shown in the figure below:
XOR operator
^
called the exclusive OR operator, and its operation rules are:
- If the values on the left and right sides of the sign are different, the result of this bit is 1, otherwise it is 0
That is: 0^0=0; 0^1=1; 1^0=1; 1^1=0
Let's continue to take 15 and 13 as examples, and look at the calculation steps of 15^13
- Convert decimal to binary
- XOR binary
The calculation process is shown in the figure below:
Problem solving
With the above knowledge to pave the way, let's move on to the topic: has a decimal integer, find the number of 1 in its binary number.
analyze
Before solving this problem, let's analyze such a scenario first:
If an integer is not equal to 0, then at least one bit in the binary representation of the integer is 1.
Assuming that the rightmost digit of this number is 1, then when 1 is subtracted, the last digit becomes 0 and all other digits remain unchanged. That is, the last bit is equivalent to a negation operation, from 1 to 0.
Next, suppose that the rightmost digit of this number is 0:
If in the binary representation of the integer, the rightmost 1
is located at the m
bit, then subtract 1 when:
m
from 1 to 0- All 0s after bit
m
- All bits before the mth bit in the integer remain unchanged
Let's give an example:
A binary number 01010000
, its 4th digit is the first 1 from the lowest digit, after subtracting 1:
- Bit 4 becomes 0
- The four 0s behind it all change to 1.
- All the bits before it remain unchanged
The results thus obtained are 01001111
, to decimal as 79
.
in conclusion
In the two cases we analyzed earlier, we found that subtracting 1 from an integer turns the rightmost 1 into 0. If there are still 0s on its far right, all 0s become 1 and all the bits on its left remain unchanged.
Next, we take an integer and the result of subtracting 1 from it and do the bitwise AND operation , which is equivalent to changing its rightmost 1 to 0. Let's take the previous 01010000
as an example. The result of subtracting 1 is 01001111
. We then perform the bitwise AND operation on both of them, and the result is: 01000000
.
After observation, we found that: changing the 1 on the far right of01010000
01000000
.
Ideas and coding
Seeing this, I think all developers have already seen the idea of solving this problem 🤓.
That's right, the idea is: subtract 1 from an integer, and do the -bit AND operation with the original integer, which will change the rightmost 1 of the integer to 0.
Then, as many times as there are 1s in the binary representation of an integer, this operation can be performed as many times until the whole number becomes 0. We count each operation to get the answer to this question.
Based on this idea, we can happily code, the code is as follows:
export default class BinaryOperation {
/**
* 获取二进制中1的个数
* @param decimalVal 十进制数
*/
public getBinaryOneNum(decimalVal: number): number {
let count = 0;
// 十进制数不为0,代表其二进制表示中仍存在1
while (decimalVal !== 0) {
// 二进制中所存在的1的总数+1
count++;
// 对十进制数与其-1后的数进行位与运算
// 得出结果后替换原十进制数,进行下一轮计算,直至十进制数为0
decimalVal = decimalVal & (decimalVal - 1);
}
// 返回结果
return count;
}
}
Finally, we write a test case to verify whether the above code can work normally, as shown below:
import BinaryOperation from "../BinaryOperation.ts";
const binaryOperation = new BinaryOperation();
const result = binaryOperation.getBinaryOneNum(80);
const result2 = binaryOperation.getBinaryOneNum(-80);
console.log(`80的二进制表示中有${result}个1`);
console.log(`-80的二进制表示中有${result2}个1`);
The result of the operation is shown in the figure below:
Sample code address: BinaryOperation.ts , BinaryOperation-test.ts
The result of the operation is consistent with the number of 1 in the binary number we manually calculated😋
-80
We calculated its binary representation in the previous chapter as10110000
. We talked about how many bits the binary occupies in the computer depends on its word length. We only need to indicate its sign bit when writing, and there are more high bits. The 1 can be omitted.Here, we calculate
-80
in the binary representation of 0617f513c349c9. We add 5 0s here to know that its word length is27 + 5 = 32
.
Write at the end
At this point, the article is finished sharing.
I amazing programmer , a front-end development engineer.
If you are interested in me, please visit my personal website to learn more.
- If there is an error in the article, please correct it in the comment area. If this article helped you, please like and follow it😊
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。