【发布时间】:2019-12-09 08:53:33
【问题描述】:
我使用 memcpy 将多个字节合并为一个整数。该代码似乎有效,并且值可以毫无问题地用于进一步计算。但是如果我用 cout 显示结果,值显示为十六进制:
代码:
int readByNameInt(const char handleName[], std::ostream& out, long port, const AmsAddr& server)
{
uint32_t bytesRead;
out << __FUNCTION__ << "():\n";
const uint32_t handle = getHandleByName(out, port, server, handleName);
const uint32_t bufferSize = getSymbolSize(out, port, server, handleName);
const auto buffer = std::unique_ptr<uint8_t>(new uint8_t[bufferSize]);
int result;
const long status = AdsSyncReadReqEx2(port,
&server,
ADSIGRP_SYM_VALBYHND,
handle,
bufferSize,
buffer.get(),
&bytesRead);
if (status) {
out << "ADS read failed with: " << std::dec << status << '\n';
return 0;
}
out << "ADS read " << std::dec << bytesRead << " bytes:" << std::hex;
for (size_t i = 0; i < bytesRead; ++i) {
out << ' ' << (int)buffer.get()[i];
}
std::memcpy(&result, buffer.get(), sizeof(result));
out << " ---> " << result << '\n';
releaseHandle(out, port, server, handle);
return result;
}
结果:
Integer Function: readByNameInt():
ADS read 2 bytes: 85 ff ---> ff85
我使用一个几乎相同的函数来创建一个浮点数。这里的输出没有问题。 值如何显示为整数?
问候 蒂尔曼
【问题讨论】:
-
那是因为
std::hex。再次将std::dec传递给流以将其设置回十进制。 -
请不要将
std::unique_ptr用作简单的自删除指针,而是将智能指针视为所有权。在你的情况下,我宁愿推荐std::vector<uint8_t>。