【问题标题】:convert unsigned integer to unsigned char *将无符号整数转换为无符号字符 *
【发布时间】:2013-06-28 14:42:58
【问题描述】:

我想从 unsigned int 获取值到 unsigned char *,我的逻辑给出了错误的值

unsigned int Address = 0x0a5b0644; // this value is getting ss fun parameter
m_Address        = (unsigned char*)Address;  // this logic wrote in side C++ file

unsigned char * m_Address; // this is declared inside H file

这里的 m_Address 没有得到值 0x0a5b0644

我能想出一些办法吗

【问题讨论】:

  • 它获得了什么价值
  • 嗯,这可能是reinterpret_cast<> 有帮助的情况吗?
  • 我得到一些垃圾值 0xFFFF80
  • 请说明您如何将m_Address 的值确定为0xFFFF80。我怀疑问题出在那儿。也许0xFFFF80m_Address地址 而不是它的值?

标签: c++ c visual-c++


【解决方案1】:

从整数类型转换为指针将由实现定义。

如果您确实需要无符号整数类型来存储指针,请在<cstdint> 中使用uintptr_t(或intptr_tfor 有符号整数类型)。它们在 C++11 中作为可选功能引入。它们能够转换为void * 类型并转换回来。

【讨论】:

  • @Griwes:他们是。参见 C11 中的第 7.20.1.4 节(与 C99 相同)。
【解决方案2】:

你可以试试以下 假设 unsigned int 为 4 个字节,{0x0a, 0x5b, 0x06, 0x44}

unsigned char bytes[11];// the number of charactoer in the string + a null terminating
sprintf(bytes, "%#04x", Address); //<here it will print it

【讨论】:

    猜你喜欢
    • 2011-06-14
    • 1970-01-01
    • 2012-05-10
    • 2012-01-09
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    相关资源
    最近更新 更多