且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

简单但难以转换的价值观。

更新时间:2023-02-27 09:28:49

这里存在许多问题:字符数量在字节边界上对齐,但整数不对齐 - 它们在字边界上对齐。 br />
这意味着基于char的值的地址可以是0,1,2,3,4,5,6 ......但是整数的地址只能是0,4, 8,16,...

其原因与处理器的工作方式以及内存的实际处理方式有关。试图将整数值填充到基于字符的地址中很容易导致其他内存损坏,或错误的值进入错误的位置。

如果不是这样,那么你可以去:

There are a number of problems here: char quantities are aligned on byte boundaries, but integers aren't - they are aligned on word boundaries.
What that means is that the address of a char based value can be 0, 1, 2, 3, 4, 5, 6 ... but the address of an integer can only be 0, 4, 8, 16, ...
The reason for this has to do with how the processor works and how memory is actually addressed. Trying to "stuff" an integer value into a char based address can easily end up with other memory getting corrupted, or the wrong values going into the wrong locations.
If that wasn't the case, you could just go:
int *pi = (int *)a;
*pi = 0xff00;

但是......即使这样做起因为地址很好也会有另一个问题:Endianness。 PC处理器是所谓的Little Endian,这意味着它将值的最低有效字节存储在最低阶地址中:因此该值将以错误的方式进行,在[0]中为0x00,并且[1]中的0xFF。 (即使不是这样,因为现在大多数处理器都是32位或64位,很少有16位,它仍然无法在正确的位置获得正确的值。



但是......你可以这样做:

But...even if that worked because the addresses were fine there would be another problem: Endianness. The PC processor is what is called "Little Endian", which means that it stores the least significant byte of a value in the lowest order address: so the value would go in the wrong way round, with 0x00 in a[0], and 0xFF in a[1]. (Even if it wasn't, since most processors are 32 or 64 bit these days with very few being 16 bit, it would still not get the right values in the right locations.

But...you can do it:

unsigned char a[2];
int i = 0xFF00;
a[0] = (unsigned char) (i >> 8);
a[1] = (unsigned char) (i & 0xFF);

这可能不是一件有用的事情!:笑:

It's just probably not a useful thing to do! :laugh: