When I went to Huawei for an interview, I didn’t prepare well; I didn’t ask or check the interview process clearly. As a result, I was asked to do the questions on the computer as soon as I passed, which was really a bit unprepared. The author is a Java Web engineer who is good at front-end, and the basic low-level programming knowledge has long been unfamiliar. The computer-based test question came up with this question about bit operations. It is supposed to be very simple and the principle is very clear to me. However, since I have not done bit operations for many years, and I have never done any Java bit operations, the result is really Disgraceful...
The computer test time limit is one hour. The language can be C or Java. What other scripting language can I choose? It took me nearly three hours to finish the question in Java. I feel ashamed...I will use JS when I come back. I have re-implemented a simple version and posted it today.
The question is: Loop through each group of two numbers hex and n (0<=n<31). Hex is a hexadecimal number. What we have to do is to invert the nth digit of hex, and then Output the corresponding result in hexadecimal format.
I won’t go into details of the process that took me more than two hours. Here is the implementation of js, which is a very simple basic knowledge of bit operations. The principle is simple, just shift 1 to the left by n bits, and then XOR it with the original number:
function bitOper(hex, n){ var num = parseInt(hex); num ^= (1<<n); return num.toString(16); } console.log(bitOper(0x1234, 3)); //123c
Due to the 32-bit limitation of the js integer type, the above example code only supports the simple case of n<31 (bit 31 is the sign bit).