I use memcpy to merge multiple bytes into an integer. The Code seems to work and value can be used for further calculations without any problems. But if I display the result with cout, the value is displayed as hex:
Code:
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;
}
Result:
Integer Function: readByNameInt():
ADS read 2 bytes: 85 ff ---> ff85
I use an almost identical function to create a float. Here the output works without problems. How can the value be displayed as an integer?
Greeting Tillman
That's because you changed the base of the output in the following line:
out << "ADS read " << std::dec << bytesRead << " bytes:" << std::hex;
The std::hex
in the end of the line will apply to every subsequent input stream to out
.
Change it back to decimal before printing the last line:
out << " ---> " << std::dec << result << '\n';