20 bit arithmetic skills that good programmers have to know

Source: Internet
Author: User
Tags arithmetic

A lifting bit operation, people often think of its efficiency, whether embedded programming or optimize the system's core code, the proper use of bitwise operations is always a fascinating means, or when you are looking for a job, write the appropriate bit in the code will also allow your program to add a glimmer of light, initially when I read "The beauty of programming" to ask "1 of the number "When, I began to think that the bit arithmetic is so beautiful, later read" Hacker's Delight ", regrets to Henry S.warren put the use of the bit so shadowy, a lot of procedures are very subtle, I think in a common program in a large number of people who use such code is crazy. But it's still necessary to master the simple bit arithmetic, so today I'm writing this blog to share some of the bit-computing skills I've accumulated, which are not like "1 number" techniques, but a basic line-and-column technique.
Welcome to my bittricks
1. Get int type max value [CPP]View plain copy int getmaxint () {return (1 << 31)-1;//2147483647, due to precedence relationship, parentheses cannot be omitted} Another way of writing [CPP]View plain copy int getmaxint () {return ~ (1 << 31);//2147483647}Another way of writing [CPP]View plain copy int getmaxint () {//Some compilers do not apply return (1 << 1)-1;//2147483647}C language does not know when an int occupies several bytes [Java]View plain copy int getmaxint () {return (unsigned int)-1) >> 1;//2147483647}2. Get the int type minimum value [CPP]View plain copy int getminint () {return 1 << 31;//-2147483648}Another way of writing [CPP]View plain copy int getminint () {//Some compilers do not apply return 1 << -1;//-2147483648}3. Get the maximum of a long type
C language version [CPP]View plain Copy long Getmaxlong () {return (unsigned long)-1) >> 1;//2147483647}Java version [Java]View Plain

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.