0

可能重复:
将 int 存储在 char 数组中?

我想将 4 个 8 位无符号字符加载到 32 位整数。并将 32 位整数存储到无符号字符指针。这怎么可能?下面的示例用法;

int 32bitint1= 0xff000000 | (uchar1<<16) | (uchar2<<8) | uchar3;
int 32bitint2= 0xff000000 | (uchar4<<16) | (uchar5<<8) | uchar6;
//then this 32-bit integer to uchar pointer;
ucharpointer[0] = 32bitint1;
ucharpointer[4] = 32bitint2;//is this possible?or how
4

2 回答 2

1

存储:(将 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(&reg,c);   

    c[0] = 'e';
    printf("%c",c[0]);  //it prints 'e'

    load(&reg,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(&reg,c);

    unsigned char *cpointer = (unsigned char *) &reg;

    for(int i=0;i<4;i++)
    {
        printf("%c",cpointer[i]);  //access the 4 chars by a char pointer
    }
    return 0;
}

请注意,您将以这种方式获得输出“dcba”,因为内存地址是以相反的顺序生成的。

于 2012-12-18T10:41:32.893 回答
0

假设字节是大端读取的,存储每个 4 字节形成 32 字节为

uint32_t bit_32 = ((uint32_t)uchar[0] << 24) |  ((uint32_t)uchar[1] << 16) | ((uint32_t)uchar[2] << 8) | ((uint32_t)uchar[3])

将 32 位整数存储为无符号字符指针,

unsigned char *ptr = &bit_32;
于 2012-12-18T10:28:16.590 回答