C++:当我将值分配给缓冲区时,它不起作用

C++: When I assign the values to a buffer, it doesn't work

本文关键字:缓冲区 不起作用 分配 C++      更新时间:2023-10-16

好的,所以我有一段代码。这会将标头的内容插入缓冲区:

buffer = (uint8_t*)malloc(totalSize);
buffer[0] = ((header.sequenceNumber >> 24) & 0xFF);
buffer[1] = ((header.sequenceNumber >> 16) & 0xFF);
buffer[2] = ((header.sequenceNumber >> 8) & 0xFF);
buffer[3] = (header.sequenceNumber & 0xFF);
buffer[4] = ((header.ackNumber >> 24) & 0xFF);
buffer[5] = ((header.ackNumber >> 16) & 0xFF);
buffer[6] = ((header.ackNumber >> 8) & 0xFF);
buffer[7] = (header.ackNumber & 0xFF);
buffer[8] = ((header.connectionId >> 8) & 0xFF);
buffer[9] = (header.connectionId & 0xFF);
buffer[10] = (0 & 0xFF);
unsigned i = (((unsigned)header.ack) << 2) + (((unsigned)header.syn) << 1) + (unsigned)header.fin;
buffer[11] = (i & 0xFF);

,并且缓冲区内容完全错误。我尝试通过添加这段代码进行调试:

std::cerr << "DEBUG: Values are: " 
    << ((header.sequenceNumber >> 24) & 0xFF) << ", " 
    << ((header.sequenceNumber >> 16) & 0xF) << ", " 
    << ((header.sequenceNumber >> 8) & 0xFF) << ", "
    << (header.sequenceNumber & 0xFF) << ", " 
    << ((header.ackNumber >> 24) & 0xFF) << ", " 
    << ((header.ackNumber >> 16) & 0xFF) << ", "
    << ((header.ackNumber >> 8) & 0xFF) << ", " 
    << (header.ackNumber & 0xFF) << ", " 
    << ((header.connectionId >> 8) & 0xFF) << ", "
    << (header.connectionId & 0xFF) << ", " 
    << (0 & 0xFF) << ", " 
    << (i & 0xFF) << endl;
std::cerr << "DEBUG: Buffer header is: " 
    << buffer[0] << ", " << buffer[1] << ", " << buffer[2] << ", " 
    << buffer[3] << ", " << buffer[4] << ", " << buffer[5] << ", "  
    << buffer[6] << ", " << buffer[7] << ", " << buffer[8] << ", " 
    << buffer[9] << ", " << buffer[10] << ", " << buffer[11] << endl;
std::cerr << "DEBUG: getBuffer ends. The size is " << totalSize 
    << ". The buffer is " << buffer << endl;

这显示在控制台中:

DEBUG: Values are: 0, 0, 48, 57, 0, 0, 0, 0, 0, 0, 0, 2
DEBUG: Buffer header is: , , 0, 9, , , , , , , ,
DEBUG: getBuffer ends. The size is 12. The buffer is

这 12 个值是正确的。但是缓冲区的 12 个元素是完全错误的。

我认为缓冲区内容是正确的,但是您将其报告给stdrr的方式失败了。

std::cerr << "DEBUG: Buffer header is: " 
          << buffer[0];

向 stderr 写入uint8_t(如果buffer类型为 uint8_t* (,但这只是一个unsigned char,因此使用 ASCII 编码。若要获取正确的整数值,请使用

std::cerr << "DEBUG: Buffer header is: " 
          << int(buffer[0]);