Graduation season has been a long time coming. . . After this June, I officially entered the society. . . I always feel like I’m not ready yet. . . . . . . . . . A huge turning point. . . Record some recent knowledge. . .
The concept of bitwise storage
In database storage, a type of binary string can be used to save multiple values. When this binary value is composed of 0 and 1, it can From right to left, each bit is added to the calculated value of 2^n and then converted into a decimal number, thereby achieving the purpose of saving multiple situations with one decimal value.
For example
There are now three different css styles that can be applied to different places, such as apps, PCs, small programs, etc.
If stored by value, use 1-3 to represent the three styles (styleType), and use 1-3 to represent the support type app, pc, and small program (supportType) respectively. Then when storing, it should be as follows Ways:
supportType | |
1,3 | |
1,2,3 | |
1 | |
... |
supportType | |
5 | |
7 | |
1 | |
... |
Practical application
① Scenario 1, in In the app environment, filtering styles means only filtering out and displaying styles that support the app.
Application principle: Numerical sum, only 1 and 1 result in 1.In other words, if we want to filter out the styles that support the app, that is, filter the styles corresponding to when the first digit in styleType is 1, that is, 1**, which means the decimal value contains 4 This number.
In js, decimal numbers can be directly ANDed, so when traversing and filtering, the code can be directly judged like this:
(item.supportType & 4 == 4)?'对应的styleType支持':'对应的styleType不支持' //注意,==优先级比&大,所以要加括号
②Scenario 2, modify supportTypeBecause what is saved to the database is a decimal array, so when modifying the corresponding relationship, you must know what is being changed Which position, and changing the value at the corresponding position, the binary representation is the process of 0 changing to 1 or 1 changing 0, but changing the decimal array is the process of increasing and decreasing the corresponding bit by 2^n.
For example:
var supportType = { //按位编码,预留3位 'app':4, 'pc':2, 'mini':1 } var supportVal = 0; i f(obj.supportmini == 1){ //支持小程序 supportVal= supportVal+supportType .mini; } if(obj.supportPc == 1){ //支持pc supportVal= supportVal+ supportType .pc; } obj.supportVal= supportVal;
Finally, just save the corresponding decimal number in the database.
For more scenes, refer here.
The above is the detailed content of The concept and examples of bitwise storage. For more information, please follow other related articles on the PHP Chinese website!