Specific bit inversion (JS implementation)

Source: Internet
Author: User

to Huawei interview, did not prepare for the job, the process of the interview did not ask clear also did not check, the results of a past let on the machine to do the problem, really a bit unprepared. The author is good at the front end of the Java Web Engineer Ah, basic knowledge of the underlying programming is already unfamiliar. Machine test questions encountered this bit operation of the topic, supposedly is very simple, the principle of the author is also very clear, but because it is really good for many years have not done bit operation, Java bit operation is no operation, so the result is not decent ...

Machine test time is one hours, language optional C or Java also has a scripting language, the author spent nearly three hours, only with Java reluctantly to make the problem, ashamed ashamed ... Back to the use of JS re-implemented a simple version, today to collate the paste out.

The title is: loop input each group of two number hex and N (0<=n<31), Hex is a 16 decimal number, we have to do is to reverse the nth position of hex, and then output the corresponding result in 16.

I toss two hours of the process will not repeat, here to give the implementation of JS, very simple bit operation of basic knowledge. The principle of a wordy, is to put 1 by the bit to the left of N-bit, and then the original number is different or on the line:

function Bitoper (hex, N) {    var num = parseint (hex);     Num ^= (1<<n);    return num.tostring (16);} Console.log (Bitoper (0x1234, 3));    123c
because the JS integer type has only a 32-bit limit, the above example code only supports the simple case of n<31 (the 31st bit is the sign bit).



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.