加载/存储8位和32位值之间

时间:2012-12-18 10:16:07

标签: c++ c

  

可能重复:
  Store an int in a char array?

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

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

2 个答案:

答案 0 :(得分:1)

商店 :(将4个字符存储到unsigned int中)

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;
}

加载 :(从unsigned int加载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',因为内存地址的顺序相反。

答案 1 :(得分: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;