Home > Article > Backend Development > In-depth understanding of endianness and type conversion in C/C++
If you talk about byte order and type conversion separately, everyone may think it is very simple, but they will not understand it deeply. If we combine them and discuss them, maybe we will understand them thoroughly.
If you don’t understand the basics of byte order and type conversion, you can refer to the following blog:
https://my.oschina.net/u/1783725/blog/647973 Large and small byte order
https: //my.oschina.net/u/1783725/blog/700970 Type conversion
Before getting into the topic, a quick sentence:
Different system digits correspond to different byte sizes of data types
Details Introducing the connection between the two
Byte order: The memory of operation is the rule for storing the data we see in memory.
Big endian: Big endian is valid, high-bit data is put into low-address memory first, and low-bit data is put into high-address memory; Little endian: little-endian is valid, low-bit data is put into low-address memory first, and then high-bit data is placed When entering high address memory
When operating memory (such as: memcpy), you need to consider the byte order
Type conversion: The operation is to read the data, which is the data to be read from the memory, according to the type of bytes Convert size.
The ones with many digits are converted into those with small digits (the high-order data will be truncated, leaving the position data), and those with small digits are converted into those with many digits (the high-order data will be filled with 0).
An example to understand them
1. Assignment has nothing to do with byte order. When operating memory (memcpy), you need to consider byte order
1: Assign 0xABCDEF1234 of unsigned long long type to unsigned long type Variables, regardless of byte order
2: unsigned long long type 0xABCDEF1234 variable uses memcpy to short type variable, found to be 0, related to byte order
The code is as follows:
#include <stdio.h>int main(int argc, char *argv[]) { unsigned long long ullVar = 0xABCD1234; unsigned long ulVar1 = 0; unsigned long ulVar2 = 0; /*memcpy操作内存时,需要考虑系统的大小字节序,如果是大字节序的话,高位的数据保存在低地址上*/ memcpy(&ulVar1,&ullVar,sizeof(ulVar1)); /*赋值时,就是讲读出的数据按照要赋值的数据类型的大小进行转换*/ ulVar2 = ullVar; printf("ulVar1=%x ulVar2=%x \n",ulVar1,ulVar2); //输出:ulVar1=0 ulVar2=abcd1234 return 0; }