2017-05-17 61 views
1

好的,所以我有一段代碼。這會將標題的內容插入緩衝區中:C++:當我將值賦給緩衝區時,它不起作用

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個元素是完全錯誤的。

+0

malloc?你正在編寫C++。使用std :: vector。 –

回答

1

我認爲緩衝區內容是正確的,但是您將其報告給stderr的方式失敗。

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

寫入uint8_t到stderr(如果bufferuint8_t*類型的),但是這只是一個unsigned char因此使用ASCII編碼。要獲得正確的整數值,請使用

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

太好了。我改變了一點,到(int)緩衝區[0],它的工作原理。 – NormalGuy

+0

@NormalGuy很高興幫助。 Btw,'int(buffer [0])'是C++風格,'(int)buffer [0]'是古老的C風格並且不推薦(但是你似乎是C黑客,因爲你使用malloc )')。 – Walter

相關問題