如何从存储在字节数组中的字节中检索值?

时间:2015-12-27 10:34:56

标签: c arrays pointers bit-manipulation bit

我试图在字节数组中存储8个字节来存储指针的值。

int main() {
    unsigned long a = 0;
    char buf[8];
    int i = 0;
    int *p = &i;
    a = (unsigned long)p;

    while (i < 8)
    {
        buf[i] = (a >> (8 * i)) & 0xFF;
        i++;
    }
    a = 0;
    i = 0;
    while (i < 8)
    {
        a = ?
        i++;
    }
    p = (int *)a;
}

第一个循环存储p的连续字节,在a中转换为usigned long,但我不知道如何在第二个循环中检索该值。有人有线索吗?

1 个答案:

答案 0 :(得分:1)

这是您的反码:

a = 0;
while (i < 8)
{
    a |= ((unsigned long)buf[i] & 0xff ) << (8 * i);
    i++;
}