2016-01-07 71 views
0

我有2種方法用於將字符轉換爲它們的8位字節值。在第一個它給出了正確的答案,但在第二個它給了額外的0,所以我不得不ba.size()-1。 我的問題是爲什麼我必須在第二個這樣做?我知道這很可能是/ 0終結者。如果我沒有錯?還有沒有更好的方法來做到這一點?Qt5將字符轉換爲8位無符號值

// very simple test if we can take bytes and get them in decimal (0-255)format: 
    QByteArray ba("down came the glitches and burnt us in ditches and we slept after we ate our dead..."); 
    for (int i = 0; i < ba.size(); ++i) 
    qDebug() << "Bytes are: "<< static_cast<quint8>(ba[i]); 
    // very simple second way to do it... 
    int j = 0; 
    while (j < ba.size()-1){ 
    qDebug() << "Bytes are: "<< static_cast<quint8>(ba[++j]); 
} 
+0

不應該兩種方式都有相同的確切結果嗎?這是主要的問題,如果它不明確... –

回答

3

不同之處在於無效使用增量操作。當你使用++j時,你已經有價值1,所以你永遠不會得到0索引。你也得到最後一個大於數組大小的索引。正確的方法是:

qDebug() << "Bytes are: "<< static_cast<quint8>(ba[j++]); 
+0

你的權利,這是一個小的混亂我沒有注意到:)謝謝... –

相關問題