c++ - 将 unsigned short/int 转换为 char *

标签 c++ qt casting char qbytearray

我有这样的功能

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<char*>Port 的操作或 reinterpret_cast<char*>RequestId .

最佳答案

你必须确保 QByteArray &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 ));

关于c++ - 将 unsigned short/int 转换为 char *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28755644/

相关文章:

c++ - 内存静态变量存储在哪里?

c++ - 与 Clang 和 Boost 1.48 一起工作的多播委托(delegate)/信号库?

c++ - 使用Qt的元对象系统获取对象实例类名称

javascript - 如何在 C++ 中获取 QML 方法的源代码?

java - id存储在map中的线程的run方法

c++ - wxWidgets C++ - 在对话框中动态包装 wxStaticText

c++ - 简单记录器实现 C++ 中的详细级别

c++ - 在子 QWidget 中修改父 QWidget

计数变更程序 - C

C 结构是否会干扰类型转换?