SoFunction
Updated on 2025-04-10

JS implements the principle and example of specific bit inversion

When I went to Huawei for an interview, I didn’t prepare well; the interview process was not cleared or checked, and as a result, I was caught off guard when I went on the computer. The author is a Java Web engineer who is good at front-end, and his basic underlying programming knowledge has long been unfamiliar. When I encountered this bit operation question in the computer test, it was very simple, and the author was very clear about the principle, but since I hadn't done bit operation for many years, and I had never done Java bit operation, so the result was really indecent...

The computer test time is one hour. The language can be selected as C or Java. What scripting language is there? It took me nearly three hours to use Java to barely get the problem done. I am ashamed... I came back and used JS to re-implement a simple version, and I compiled it today.

The question is: Loop input of two numbers hex and n (0<=n<31), hex is a hex number. What we need to do is invert the nth position of hex and then output the corresponding result in hex form.

I won’t go into details after more than two hours of tossing. Here I give you the implementation of js, which is a very simple basic knowledge of bit operations. The principle is to shift 1 to the left n bits by bits, and then just XOR with the original number:

function bitOper(hex, n){ 
var num = parseInt(hex); 
num ^= (1<<n); 
return (16); 
} 
(bitOper(0x1234, 3)); //123c

Since the js integer type has only 32 bits limitation, the above example code only supports the simple case of n<31 (bit 31 is the sign bit).