[英]boost async_read_some reads wrong buffer
am trying to receive to a queue->buffer
where queue->buffer
is char * buffer = new char[1024]
正在尝试接收queue->buffer
,其中queue->buffer
为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 :- 并使用此方法将bytes数组转换为十六进制:
#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! 那些ffffff
错了! maybe there is a bad allocation of some sort?! 也许分配不好?!
which is wrong those
ffffff
is wrong! 那些ffffff
错了!
That's because, on your platform, char
is signed and so the byte values are treated as signed types. 这是因为在您的平台上, char
是带符号的,因此字节值被视为带符号的类型。 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. 设置了最高位的任何值(例如第二个值84
)都将被视为负值,并且向int
的转换会将所有新位设置为1以保留负值。 That gives the ffffff
. 这就是ffffff
。
One option is to use unsigned char
rather than char
everywhere you're dealing with binary data. 一种选择是在处理二进制数据的任何地方都使用unsigned char
而不是char
。
Another option is to convert to unsigned char
rather than int
for output. 另一种选择是将其转换为unsigned char
而不是int
以进行输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.