C language exercise question 52: Write a function to determine whether the current machine is big endian or little endian

Code:

method 1:

#include<stdio.h>
int check_sys() {
	int a = 1;
	return *(char*)&a;//小端retrun 1 大端return 0;
}
int main() {
	if (check_sys() == 1) {
		printf("小端\n");
	}
	else
		printf("大端\n");
}

Method 2 (Using Consortium):

int check_sys() {
	union
	{
		char c;
		int i;
	}u;
	u.i = 1;
	return u.c;
}
int main() {
	if (check_sys() == 1)
		printf("小端\n");
	else
		printf("大端\n");
	return 0;
}

The address taken here is first dereferenced after aforced conversion , that is, the first byte of the address is taken out to see the value. Referring to the table above, if it is little-endian storage, then the first byte in the address is , otherwise it is . In this way, the judgment of big and small ends is realized.char*aa0100

Understanding endianness:

 

Big-endian byte order refers to the byte order in which data is stored on the computer.

Guess you like

Origin blog.csdn.net/2301_77479435/article/details/132837674