【问题标题】:How to read 64 bits from a pointer to an 8 bit value如何从指向 8 位值的指针中读取 64 位
【发布时间】:2016-02-26 19:17:13
【问题描述】:

我创建了一个数组来表示虚拟内存,并且这个数组有一个 uint8_t*。我试图一次访问 64 位,并将其设置为等于一个值。它只占用第一个字节,我不知道如何让它占用整个 64 位。

control->value = memory[pc + 2];

我知道这会将控件的值设置为 pc+2 处的内存数组(我要读取的 64 位的开头)

我只是不知道如何让这段代码将 64 位输入控制-> 值 (a uint64_t)

【问题讨论】:

  • 读取 8 个字节并使用 bitops 合并它们。 This answer 应该有帮助。
  • 添加有关变量数据类型的详细信息有助于获得清晰的概念。
  • @AbhishekChoubey:它们隐藏在文本中。
  • 通过将“value”的数据类型从uint8_t*更改为uint64_t*。
  • @AbhishekChoubey: ... 这会调用未定义的行为。

标签: c arrays pointers indexing casting


【解决方案1】:

执行此操作的最简洁方法是一次读取一个字节,然后移位和 OR 中的值。

如果 MSB 在前:

control->value = (uint64_t)memory[pc + 2] << 56;
control->value |= (uint64_t)memory[pc + 3] << 48;
control->value |= (uint64_t)memory[pc + 4] << 40;
control->value |= (uint64_t)memory[pc + 5] << 32;
control->value |= (uint64_t)memory[pc + 6] << 24;
control->value |= (uint64_t)memory[pc + 7] << 16;
control->value |= (uint64_t)memory[pc + 8] << 8;
control->value |= (uint64_t)memory[pc + 9];

如果 LSB 在前:

control->value = (uint64_t)memory[pc + 2];
control->value |= (uint64_t)memory[pc + 3] << 8;
control->value |= (uint64_t)memory[pc + 4] << 16;
control->value |= (uint64_t)memory[pc + 5] << 24;
control->value |= (uint64_t)memory[pc + 6] << 32;
control->value |= (uint64_t)memory[pc + 7] << 40;
control->value |= (uint64_t)memory[pc + 8] << 48;
control->value |= (uint64_t)memory[pc + 9] << 56;

强制转换对于确保左移不会“掉出边缘”是必要的。

【讨论】:

  • 请永远不要做第一个选项。它不便携,违反了严格的别名规则,通常是个坏主意。
  • 我只是不想因为太露骨而侮辱你 ;-)
  • 这正是我想弄清楚的,非常感谢!
  • @Anon 很高兴我能帮上忙。如果您觉得有用,请随时 accept this answer
【解决方案2】:

通过以下方式,您可以使用uint8_t* 访问 64 位值

int main()
{
    uint64_t value = 100000000000;
    printf("%lld\n",value);
    uint8_t* ptr = (uint8_t*)&value;     
    printf("%lld\n",*((uint64_t*)(ptr)));//While accessing the value you need typecast it back to uint64_t type.
    return 0;
}

希望这会有所帮助。

【讨论】:

  • 调用未定义的行为。
  • 它如何显示未定义的行为,请解释一下。
  • (如果您回复其他评论,请使用@name 来称呼此人。只需使用tour 并遵守网站规则) 说:格式字符串错误。对于另一个(可能更严重的)UB,我被代码误导了。该代码仅显示您可以将指向一种类型的指针转​​换为 unsigned char * 并返回。不是如何解组uint64_t。你没有回答问题。
【解决方案3】:

考虑以下程序:

#include <stdio.h>
#include <stdint.h>
struct some_struct{
    uint64_t value;
};
int main(void){
    uint64_t memory[10] = {111111111,22222222,0x1111111111111111,444444444,5,6,7,8,9,20};
    struct some_struct *control = malloc(sizeof(struct some_struct));
    int pc = 0;

    control->value = memory[pc+2];
    fprintf(stderr, "ptr = %llu, %llu\n", control->value, memory[2]);
}

这里我试图访问“内存”的第三个元素,它是一个数组
64 位整数。
希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 2019-10-19
    • 1970-01-01
    • 2013-01-11
    • 2012-07-16
    • 2011-01-31
    • 2015-07-21
    相关资源
    最近更新 更多