A case analysis of js bit operation

jsThe median operation is less used. Although the bit operation is more efficient, it cannot be used in actual projects.

I saw a piece of code by chance, and thought it was quite ingenious (maybe I just thought it was ingenious), so I analyzed it.

let res = (Math.floor(Math.random() * 0xff) << 16)
        + (Math.floor(Math.random() * 0xff) << 8)
        +  Math.floor(Math.random() * 0xff)

This code will return a random color value, and the result can be directly used to display the color after being converted into hexadecimal.

analyze

We know Math.random()that the result of converting to decimal is [0, 1), converting to binary is0xff2551111 1111

So it can be known Math.random() * 0xffthat the range of is [0, 255), that is [0, 0xff).

And the maximum value of the color is rgb(255, 255, 255), ie 0xffffff.

Convert to hexadecimal is 1111 1111 1111 1111 1111 1111.

Then 0xff << 16 is 1111 1111 0000 0000 0000 0000.

Empathy

0xff << 8 is1111 1111 0000 0000

0xff is1111 1111

Therefore, the maximum value of the above code res is the sum of the three1111 1111 1111 1111 1111 1111

That is, 0xffffffthe minimum value is naturally0x000000

So the above code will return a random color value.

Use to convert to hexadecimal color value in js

// 先获取16进制字符串
let hex = res.toString(16);
// 因为css中颜色需要用6位16进制,有可能随机生成的res转为16进制后不够6位,所以需要在前面补0
let zero = '000000';
let zeroCount = 6 - hex.length;
// 拼接最终的颜色值 例如 #ff0000
let color = '#' + zero.substr(0, zeroCount) + hex;

Guess you like

Origin blog.csdn.net/mochenangel/article/details/119361332