比变量小的指针类型

Pointer type of smaller size than variable

使用嵌入式系统,为了在递增序列中获得更高的分辨率,我有两个变量,一个总是跟随另一个。

具体来说,我使用 8 位变量设置目标值,但要从一个点(当前值)到另一个点,我使用 32 位步长来完成。

例如(这是一个愚蠢的例子,但它只是为了展示我想如何使用它,在我的代码中有一些临时化需要 32 位变量来允许缓慢的变化):

/* The variables */
char goal8bits;         // 8 bits
long int current32bits; // 32 bits    
char current8bits;      // 8 bits    
long int step32bits;    // 32 bits

/* The main function (in the real code that is done periodically with a specific period) */
current32bits = CONVERT_8BITS_TO_32BITS(current8bits);  // E.g: 0xAB -> 0xABABABAB
if (goal8bits < current8bits) {
   current32bits += step32bits;
}
current8bits = CONVERT_32BITS_TO_8BITS(current32bits);  // E.g: 0x01234567 -> 0x01

/* Other parts of the code */
I use current8bits to know the current value in the middle of a transition.

我的问题是我是否可以使用一个字符指针并使它指向 32 位变量 1,这样我就不需要每次更改它时都更新它。 前面的示例将如下所示:

/* The variables */
char goal8bits;         // 8 bits
long int current32bits; // 32 bits
char *current8bits = (char *)&current32bits;      // Pointer to 8 bits
long int step32bits;    // 32 bits

/* The main function (in the real code that is done periodically with a specific period) */
if (goal8bits < *current8bits) {
   current32bits += step32bits;
}

/* Other parts of the code */
I will use *current8bits to know the current value in the middle of a transition.

你认为这样做有什么问题吗?它会导致字节序问题吗?

谢谢!

是的,它是字节序相关的代码,为了使其可移植,您可以使用掩码和左移运算符:

uint8_t goal8bits = 0x01;               // 8 bits
uint32_t current32bits = 0x01234567;    // 32 bits
uint32_t step32bits = 1;                // 32 bits

if (goal8bits < ((current32bits & 0xFF000000) >> 24)) {
    current32bits += step32bits;
}

如果您知道系统的无字节序,并且它是静态的,您必须从

select
char *current8bits = (char *)&current32bits;

char *current8bits = (((char *)&current32bits)+3);

如果你必须测试它,而你的系统不能给你这样的信息,你可以在应用程序启动时获取它

uint32_t temp = 0x01020304;
uint8_t *temp2 = (uint8_t *)(&temp);
if (*temp2 == 0x01)
{
   char *current8bits = (char *)&current32bits;
}
else
{
   char *current8bits = (((char *)&current32bits)+3);
}

另一个很好的解决方案是投票最多且已回答的答案 HERE