Determine whether the CPU is a small-end storage (Little endian) or a large-end storage (Big endian) mode.

Source: Internet
Author: User

First version:

// Return true in big-endian machinesbool check_big_endian1 () {int a = 0; int * p = & a; * (char *) p = 1; return! = 1 ;}

The second version of union is used:

// Return true in big-endian machinesbool check_big_endian2 () {union {int a; char B;} var; // sizeof (var) = 4var. a = 1; return var. b! = 1 ;}

Finally, let's look at a version to avoid function calls:

Static union {int a; char B;} _ s_var_endian_check = {1}; # define ISLITTLEENDIAN (_ s_var_endian_check. B = 1) # define ISBIGENDIAN! ISLITTLEENDIAN

In this way, the macro ISLITTLEENDIAN and ISBIGENDIAN can be used to read the values of static variables to determine whether it is a small-end mode or a large-end mode.

However, this is the way C is written. The inline function can be used in C ++ to avoid macro usage.



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.