【问题标题】:Convert array of bytes to uint64_t?将字节数组转换为 uint64_t?
【发布时间】:2017-03-21 06:03:58
【问题描述】:

我有一个称为内存的大字节数组,我正在尝试将其中的 8 个字节转换为 uint64_t。我正在尝试以大端方式打印数字。

到目前为止我有这个:

uint64_t value =  (uint64_t)(memory[256]) | //location contains byte 88
   (uint64_t)(memory[257]) << 8  |          //77
   (uint64_t)(memory[258]) << 16 |          //66
   (uint64_t)(memory[259]) << 24 |          //55
   (uint64_t)(memory[260]) << 32 |          //44
   (uint64_t)(memory[261]) << 40 |          //33
   (uint64_t)(memory[262]) << 48 |          //22
   (uint64_t)(memory[263]) << 56;           //11

我是这样打印的:

printf("0x%x", value);

输出为0x55667788,但我希望输出为0x1122334455667788

关于如何修复上述代码以打印0x1122334455667788的任何建议?

解决方案:打印语句需要是:

printf("0x%lx", value);

【问题讨论】:

  • 编译器是否警告过你?
  • 我不知道这个...但我在这里发现了类似的问题...stackoverflow.com/questions/4142251/…
  • 我没有,不。
  • 你是在要求编译器给你警告吗?
  • 让我试试

标签: c arrays bitwise-operators bit-shift endianness


【解决方案1】:

格式说明符%lx 有效,因为unsigned long 类型恰好在您的系统上至少有64 位。 C 标准不保证这一点,实际上它在 64 位 Microsoft Windows 上只有 32 位。 unsigned long long 保证至少有 64 位,所以你可以使用这个:

printf("0x%llx\n", (unsigned long long)value);

如果您的编译器和 C 库支持 C99 或更高版本的标准,您可以使用 &lt;inttypes.h&gt; 中定义的宏:

printf("0x%" PRIx64 "\n", value);

【讨论】:

    猜你喜欢
    • 2020-12-29
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多