C language program to determine the computer's CPU size

Source: Internet
Author: User

How can I determine whether the CPU of a computer is aligned with the big end or small-character end?

First, you must understand what is a big end and a small end.

The large-end Mode means that the high bytes of the word data are stored in the low address, while the low bytes of the word data are stored in the high address.


Small-end format: In contrast to the large-end storage format, the low-end storage format stores the low bytes of word data, and the high-end storage stores the high bytes of word data.

So how can I use a C language program to determine whether the CPU is large-end or small-end alignment?

There are several methods:

Method 1: Use the memory value of the variable directly. Some debugging skills are required here.

[Cpp] view plaincopy
# Include <stdio. h>
 
Void main ()
{
Short s = 0x1234;
Char * pTest = (char *) & s;
Printf ("% p % 0X % X", & s, pTest [0], pTest [1]);
}

Output the short variable s in the memory byte distribution in hexadecimal format.

The running result is:

0012FF7C

34 12

Method 2: Use the shared body in C:

Write a C function. If the processor is Big_endian, false is returned. If Little_endian is used, true is returned.

Bool IsLitte_Endian ()

{

Union w {

Int;

Char B;

} C;

C. a = 1;

Return (c. B = 1 );

 

}

Method 3: Forced type conversion, similar to the practice of sharing the body.

Bool IsLitte_Endian ()

{

Int wTest = 0x12345678;

Short * pTest = (short *) & wTest;

Return! (0x1234 = pTest [0]);

}

Related Article

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.