C++/C与汇编: 大小端, printf格式化数据出入栈, 64bit数据类型应用在32bit程序避坑
大小端:
大端模式,是指数据的高字节保存在内存的低地址中,而数据的低字节保存在内存的高地址中,这样的存储模式有点儿类似于把数据当作字符串顺序处理:地址由小向大增加,而数据从高位往低位放;
小端模式,是指数据的高字节保存在内存的高地址中,而数据的低字节保存在内存的低地址中,这种存储模式将地址的高低和数据位权有效地结合起来,高地址部分权值高,低地址部分权值低,和我们的逻辑方法一致。
比如整形十进制数字:305419896 ,转化为十六进制表示 : 0x12345678 。其中按着十六进制的话,每两位占8个字节。如图
在计算机系统中,我们是以字节为单位的,每个地址单元都对应着一个字节,一个字节为8bit。但是在C语言中除了8bit的char之外,还有16bit的short型,32bit的long型(要看具体的编译器)。另外,对于位数大于8位的处理器,例如16位或者32位的处理器,由于寄存器宽度大于一个字节,那么必然存在着一个如果将多个字节安排的问题。因此就导致了大端存储模式和小端存储模式。
知道为什么有模式的存在,下面需要了解下具有有什么应用场景:
1、不同端模式的处理器进行数据传递时必须要考虑端模式的不同
2、在网络上传输数据时,由于数据传输的两端对应不同的硬件平台,采用的存储字节顺序可能不一致。所以在TCP/IP协议规定了在网络上必须采用网络字节顺序,也就是大端模式。对于char型数据只占一个字节,无所谓大端和小端。而对于非char类型数据,必须在数据发送到网络上之前将其转换成大端模式。接收网络数据时按符合接受主机的环境接收。
(content above refers to https://www.cnblogs.com/Alandre/p/4878841.html ,thk for the author)
printf格式化数据出入栈, 64bit数据类型应用在32bit程序避坑:
vs2013, 32bit, release, pNow and FreezeEndTime are 64bit-long long type, IsFreeze is bool type
here are two picture that show the assembly codes which are produced by the codes in above picture
by observe the msg from console and the assembly codes, I find “printf” push the data into stack in the order that right to left, and then read the data from top to bottom in the stack. the stack top point sub length(%u), length(%u), length(%d) in turn.(in 32bit, 4 byte == %u, 4byte == %d). So in line 97, it will print pNow(32bit low), pNow(32bit high), FreezeEndTime(32bit low) and then print ‘\n’, it makes trouble to influence our judging. But in line 96 it work fine, because explicit type conversions. (I guess that other functions are the same as “printf”)
In line 101, by observeing assembly codes, we can find the comparation between the two 64bit data type is comparing the 32bit high and then comparing the 32bit low.