Use union to determine byte order

Aims to learn consortia through cases.

The full name of big endian is big endian byte order storage, which is divided into big endian byte order storage and little endian byte order storage. Why is it called byte order? It is the order in which byte is the unit.

Big-endian principle

 

The concept of big and small endian can be searched on csdn, which is very clearly explained.

The following is a code on how to use a union or pointer to determine the endianness and how to convert.

The union determines the big and small ends by taking advantage of the characteristics of the union's shared memory.

Code schematic diagram (viewed in conjunction with the code)
#include <io_utils.h>

# 判断是不是大小端,利用联合体。
#内存中存的是s的值,但是由于c共享内存,
#所以能通过c查看内存的值,从而判断1存在大端还是小端
int IsBigEndian() {
  union {
    char c[2];
    short s;
  } value = {.s=0x100};
  return value.c[0] == 1;
}
# 第二种方法,利用指针。
int IsBigEndian2() {
  short s = 0x100;
  char *p = (char *)&s;
  return p[0] == 1;
}

# 大小端转换
int ToggleEndian(int original) {
  union {
    char c[4];
    int i;
  } value = {.i=original};

  char temp = value.c[0];
  value.c[0] = value.c[3];
  value.c[3] = temp;
  temp = value.c[1];
  value.c[1] = value.c[2];
  value.c[2] = temp;

  return value.i;
}

# 利用指针实现大小端转换
int ToggleEndian2(int original) {
  char *p = (char *)&original;
  char temp = p[0];
  p[0] = p[3];
  p[3] = temp;
  temp = p[1];
  p[1] = p[2];
  p[2] = temp;

  return original;
}

int main() {
  PRINT_INT(IsBigEndian());

  int original = 0x12345678;
  PRINT_HEX(ToggleEndian(original));
  return 0;
}

 * (char*)&i means to force the int type pointer to a (char*) type pointer,
    so that the int pointer that originally pointed to four bytes becomes a char type pointer that points to one byte.
    &i means taking the address operation, but the address is a kind of pointer

Guess you like

Origin blog.csdn.net/qq_23172985/article/details/129235664