【问题标题】:Cast an unsigned short/int to char *将无符号的 short/int 转换为 char *
【发布时间】:2015-04-29 14:36:32
【问题描述】:

我有这样的功能

void UnitTestWorker::constructTestPayload(QByteArray &payload)
{
    QString List = "127.0.0.1";
    unsigned short Port = 12344;
    unsigned int RequestId = 1;
    memcpy(payload.data(),reinterpret_cast<char*>Port,sizeof(Port));
    memcpy(payload.data()+sizeof(Port),reinterpret_cast<char*>RequestId ,sizeof(RequestId ));
}

但我收到访问冲突错误,似乎我无法执行 reinterpret_cast&lt;char*&gt;Portreinterpret_cast&lt;char*&gt;RequestId 之类的操作。

【问题讨论】:

  • 你的意思是&amp;Port 重新解释演员表吗? &amp;RequestId 也一样?将unsigned shortint 转换为char* 会很不靠谱。我怀疑你的意思是使用他们的地址。
  • 即使更改为 &Port 和 & RequestID 我得到正确的东西是因为 char : 1 byte short : 2 bytes
  • 我不知道你刚才说了什么。

标签: c++ qt casting char qbytearray


【解决方案1】:

你必须确保QByteArray &amp;payload 有足够的大小来接收你字节复制到它的数据:

if (payload.size()<sizeof(Port)+sizeof(RequestId)) 
    throw exception ("Ouch !! payload too small"); 
memcpy(payload.data(),reinterpret_cast<char*>(&Port),sizeof(Port));
memcpy(payload.data()+sizeof(Port),reinterpret_cast<char*>(&RequestId) ,sizeof(RequestId ));

【讨论】:

    猜你喜欢
    • 2015-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    相关资源
    最近更新 更多