gpt4 book ai didi

c - 小端与大端的类型转换

转载 作者:行者123 更新时间:2023-11-30 15:35:18 25 4
gpt4 key购买 nike

使用下面的代码,我研究了 MS-VC++ 中的反汇编

int main() {
int a = 0x7fffee
,as; //initialization in hex
short b = 0x7fff
,bs;
//the format specifier %hp of %hd prints lower 2bytes only
printf("a(in dec) = %d : b(in dec) = %d \n",a,b);
printf("a(in hex) = %p : b(in hex) = %p \n",a,b);

as = a << 2;
printf("(a << 2) = %p \n",as);
as = (int)b;
printf("(int)b = %p \n",as);

bs = (short)a;
printf("(short)a = %hp \n",bs);
bs = (short)as;
printf("(short)as = %hp \n",bs);



return 0;
}

对以下反汇编特别感兴趣

17:       bs = (short)a; //bs gets only lower 2 bytes from a during typecast
0040B7F3 mov dx,word ptr [ebp-4]
0040B7F7 mov word ptr [ebp-10h],dx

为了将 int 类型转换为 Short,使用 dx 寄存器。在输出中我看到

a(in dec) = 8388590 : b(in dec) = 32767
a(in hex) = 007FFFEE : b(in hex) = 00007FFF
(a << 2) = 01FFFFB8
(int)b = 00007FFF
(short)a = 0000FFEE //Interested to know what will be this value in Big Endian mode
(short)as = 00007FFF
Press any key to continue

我想知道

  1. 为什么(short)a = 0000FFEE,为什么不(short)a = 007F或7FFF

  2. 大端模式下引用的 assembly 线的行为?谁能解释一下,或者我如何在 MS-VC++ 环境中将内存模型设置为大端或小端,以便我可以检查一下!

最佳答案

Why (short)a = 0000FFEE and why not (short)a = 007F or 7FFF

©ISO/IEC ISO/IEC 9899:201x编程语言——C

6.3.1.3 Signed and unsigned integers

3 ... the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

MSDN Demotion of Integers

When a long integer is cast to a short, or a short is cast to a char, the least-significant bytes are retained.

<小时/>
(short)a = 0000FFEE //Interested to know what will be this value in Big Endian mode

如上所述,它是实现定义的,但我们很难找到一个能产生除最低有效字节之外的内容的实现。

关于c - 小端与大端的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22987189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com