2012-08-03 73 views
3

我正在嘗試使用一個32位整數對4個值進行編碼的類。到目前爲止,它保存並輸出所有的值而不會丟失任何東西,但由於某種原因,按錯誤的順序。在32位整數中對4個值進行編碼

struct encoder { 
    uint32_t val; 

    encoder(uint32_t _val = 0) : val(_val) {} 

    uint32_t first(uint32_t v = 0) { 
     if (!v) return (val << (8*3)) >> (8*3); 

     val |= v; 
    } 

    uint32_t second(uint32_t v = 0) { 
     if (!v) return (val << (8*2)) >> (8*3); 

     encoder _backupval(val); 

     val = (val >> (8*1)); 
     val |= v; 
     val = (val << (8*1)); 
     val |= _backupval.first(); 
    } 

    uint32_t third(uint32_t v = 0) { 
     if (!v) return (val << (8*1)) >> (8*3); 

     encoder _backupval(val); 

     val = (val >> (8*2)); 
     val |= v; 
     //now restore 
     val = val << 8; 
     val |= _backupval.second(); 
     val = val << 8; 
     val |= _backupval.first(); 
    } 

    uint32_t fourth(uint32_t v = 0) { 
     if (!v) return (val << (8*0)) >> (8*3); 

     encoder _backupval(val); 

     val = (val >> (8*3)); 
     val |= v; 
     //now restore 
     val = val << 8; 
     val |= _backupval.second(); 
     val = val << 8; 
     val |= _backupval.first(); 
     val = val << 8; 
     val |= _backupval.third(); 
    } 
}; 

int main() { 
    encoder t; 
    t.first(6); 
    t.second(42); 
    t.third(212); 
    t.fourth(23); 

    cout << "first number: " << t.first() 
     << "\nsecond number: " << t.second() 
     << "\nthird number: " << t.third() 
     << "\nfourth number: " << t.fourth() << endl; 

} 

請注意,我正在做這個練習,而且這個程序不會在真正的程序中使用。因此,不建議替代方法來做到這一點,並且不要指出缺陷(例如,如果數字的大小超過256,會損壞另一個整數等)。

+0

你在哪裏超載了第一個()second()...? – 2012-08-03 13:30:52

+1

你試過調試過嗎?這似乎是調試器可以處理的一個非常簡單的問題。 – 2012-08-03 13:31:21

+1

你也錯過了很多返回語句。啓用額外的編譯器警告 – Zeta 2012-08-03 13:32:15

回答

5

您混合了函數的順序在fourth

uint32_t fourth(uint32_t v = 0) { 
    if (!v) return (val << (8*0)) >> (8*3); 

    encoder _backupval(val); 

    val = (val >> (8*3)); 
    val |= v; 
    //now restore 
    val = val << 8; 
    val |= _backupval.second(); 
    val = val << 8; 
    val |= _backupval.first(); 
    val = val << 8; 
    val |= _backupval.third(); // this should be called first! 
} 

這將導致加擾的返回值。先致電third,然後it will work

uint32_t fourth(uint32_t v = 0) { 
    if (!v) return (val << (8*0)) >> (8*3); 

    encoder _backupval(val); 

    val = (val >> (8*3)); 
    val |= v; 
    //now restore 
    val = val << 8; 
    val |= _backupval.third(); 
    val = val << 8; 
    val |= _backupval.second(); 
    val = val << 8; 
    val |= _backupval.first(); 
} 
相關問題