am trying to receive to a queue->buffer
where queue->buffer
is char * buffer = new char[1024]
void AsyncConnection::BeginReceive(){
m_socket.async_read_some(boost::asio::buffer(&queue->GetBuffer()[queue->GetOffset()], queue->GetBufferLength() - queue->GetOffset()), boost::bind(&AsyncConnection::EndReceive, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
and am converting the bytes array to hex using this method :-
#include <iomanip>
void output_hex(std::ostream& out, char* buf, int len) {
for (int i = 0; i < len; i++)
out << std::noshowbase
<< std::hex
<< std::setfill('0')
<< std::setw(2)
<< static_cast<int> (buf[i])
<< " ";
out << std::dec << std::endl;
}
the output looks like this :-
17 ffffff84 04 65 ffffff83 45 fffffff3 ffffffe2 ffffffdf 0f 33 ffffffa5 14 fffff
fcb 75 6f 5f ffffff89 ffffffb0 22 27 fffffffe ffffffeb fffffff2 ffffffef ffffffe
8 53 40 ffffffbe 18 ffffffa6 ffffff84 67 53 33 ffffffd6 ffffffa6 16 ffffff81 fff
fffe0 ffffffd9 05 35 ffffffab 16 ffffffc1 7f 6d 59 ffffff87 ffffffba 20
which is wrong those ffffff
is wrong! maybe there is a bad allocation of some sort?!
which is wrong those
ffffff
is wrong!
That's because, on your platform, char
is signed and so the byte values are treated as signed types. Any value with the top bit set (such as the second value, 84
) will be regarded as negative, and the conversion to int
will set all the new bits to 1 to preserve the negative value. That gives the ffffff
.
One option is to use unsigned char
rather than char
everywhere you're dealing with binary data.
Another option is to convert to unsigned char
rather than int
for output.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.