From http://blog.csdn.net/delphiwcdj/article/details/6234383
Problem: How can I use a program to determine the storage mode of the current system (large-end or small-end )? Write a C function. If the processor is big-Endian, 0 is returned. If the processor is little-Endian, 1 is returned.
Case 1: array type
- # Include <cstdio>
- Int checksystem ()
- {
- Char s [] = "1000 ";
- Return (s [0] = '1 ');
- }
- Int main ()
- {
- Checksystem () = 1? Printf ("Little-Endian/N"): printf ("big-Endian/N ");
- Return 0;
- }
Case 2: Displacement Calculation
- Int I = 1;
- If (1> 32 = 0)
- Cout <"small-end mode" <Endl;
- Else
- Cout <"big end mode" <Endl;
Is the above method correct? Why is it incorrect?
This is because the size end is strictly linked to the memory instead of making a comment on the value. If int A = 1; then a & 1 = 1 must be true, because it is calculated from the numerical point of view and has blocked the problem of size. Int A = 1; * (char *) (& A) = 1.
The following describes some effective methods.
Method 1: Use the Union type -- the feature of the Union type data can be used: the starting addresses of all Members are consistent.
- # Include <cstdio>
- Int checksystem ()
- {
- Union check
- {
- Int I;
- Char ch;
- } C;
- C. I = 1;
- Return (C. CH = 1 );
- }
- Int main ()
- {
- Checksystem () = 1? Printf ("Little-Endian/N"): printf ("big-Endian/N ");
- Return 0;
- }
Method 2: force int type conversion
- # Include <stdio. h>
- # Include <stdlib. h>
- Int main ()
- {
- Int I = 1;
- (* (Char *) & I = 1 )? Printf ("Little-Endian/N"): printf ("big-Endian/N ");
- System ("pause ");
- Return 0;
- }
Method 3: Use union and macro to define
- # Include <stdio. h>
- # Include <stdlib. h>
- Static Union
- {
- Char A [4];
- Unsigned long ul;
- } Endian = {'l ','? ','? ',' B '}};
- # Define endian (char) endian. UL)
- Int main ()
- {
- Printf ("% C/N", endian );
- System ("pause ");
- Return 0;
- }
Supplement:
The effect of the size-end mode on Union data.
- # Include <cstdio>
- Union
- {
- Int I;
- Char A [2];
- } * P, U;
- Int main ()
- {
- P = & U;
- P-> A [0] = 0x39;
- P-> A [1] = 0x38;
- Printf ("% x/N", p-> I); // 3839 (Hex .)
- Printf ("% d/N", p-> I); // 111000 00111001 14393 = (decimal)
- Return 0;
- }
Shows the analysis:
High address and low address
-- Int
0 | 0 | 56 | 57
--------
-- Char
56 | 57
----
Here we need to consider the storage mode: Big-end mode and small-end mode.
Big-Endian: Low bytes of data are stored in the high address.
Little-Endian: the low bytes of data are stored in the low address.
The space occupied by Union-type data is equal to the space occupied by the largest Member. The access to Union-type members is started at 0 from the offset of the base address of the Union, that is, the access to a consortium starts from the first address of the Union regardless of the variable. Therefore, the output result of the above program is obvious.