存储:(将 4 个字符存储到无符号整数中)
int store(uint32_t * reg, unsigned char c[4])
{
*reg = 0;
for(int i=0;i<4;i++)
{
*reg = (*reg<<8) | c[i];
}
return 0;
}
加载:(从无符号整数加载 4 个字符)
int load(uint32_t * reg, unsigned char c[4])
{
for(int i=0;i<4;i++)
{
c[i] = *reg;
*reg = *reg>>8;
}
return 0;
}
用法示例:
int main ()
{
unsigned char c[4] = {'a','b','c','d'};
uint32_t reg;
printf("%c",c[0]); //it prints 'a'
store(®,c);
c[0] = 'e';
printf("%c",c[0]); //it prints 'e'
load(®,c); //load
printf("%c",c[0]); //it prints 'a' again
return 0;
}
如果您不想将它们重新加载到 char 数组中,而是通过 char 指针访问它们,那么这里有一个示例:
int main (int argc, char const *argv[])
{
unsigned char c[4] = {'a','b','c','d'};
uint32_t reg;
store(®,c);
unsigned char *cpointer = (unsigned char *) ®
for(int i=0;i<4;i++)
{
printf("%c",cpointer[i]); //access the 4 chars by a char pointer
}
return 0;
}
请注意,您将以这种方式获得输出“dcba”,因为内存地址是以相反的顺序生成的。