c++14 integer maximum/small value

Source: Internet
Author: User

Table of Contents
    • 1. How to get the maximum value
      • 1.1. Methods of C++14
      • 1.2. How to achieve maximum value by yourself
      • 1.3. How to implement the minimum value yourself
1 How to get the maximum value1.1 Methods of C++14
Std::cout << "int\t"  << std::numeric_limits<int>::lowest () << ' \ t '  << std:: Numeric_limits<int>::max () << ' \ n ';

The output is:

int-21474836482147483647
1.2 How to implement the maximum value yourself
int max_int = (int) ((unsigned) ~0 >> 1) cout << max_int << Endl;

The output is:

2147483647

The result is the same. This line of code needs to be interpreted:

    • ~0 is reversed, all bits are set to 1
    • (unsigned) transformation is to interpret the first position from the left as an unsigned bit, to prepare for the next right move
    • >> 1 is shifted right one (divided by 2) because it is an integer of type unsigned, so the left side is 0
    • The result is then converted to the target type int, because there is no overflow, so you can definitely
1.3 How to implement the minimum value yourself
int min =-(int) ((unsigned) ~0 >> 1)-1;

Just add the symbol based on the maximum value that has been calculated, and subtract one.

Author:dean

CREATED:2016-01-14 Four 10:37

Validate

c++14 integer maximum/small value

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.