如何在以下代码中使用C ++中的1s补码?

时间:2013-11-09 09:35:14

标签: c++ complement

我想对sum +中的任何位进行1s补码,并将补码位保存在finalsum中。怎么做。使用bitvec和uint32_t类型的东西我有点弱。所以我在这里很困惑。请帮忙。

#include <iostream>
#include <string>
#include <bitset>
using namespace std;
#include <vector>
#include <stdint.h>

int main() {
int i;
string j;

std::string message = "hello "; // Some string.
std::vector<uint16_t> bitvec;
unsigned char* cp = message.c_str()+1;
while (*cp) {
   uint16_t bits = *(cp-1)>>8 + *(cp);
   bitvec.push_back(bits);
}

uint32_t sum=0;
uint16_t overflow=0;

for(auto j = bitvec.begin(); j != bitvec.end(); ++j) { 
sum += *j;
std::uint16_t; overflow = sum>>16;  //capture the overflow bit, move it back to lsb
sum &= (1<<16)-1;    //clear the overflow
sum += overflow;     //add it back as lsb
}

uint32_t finalsum=0;
for (k=0; k<=sum.length(); k++)
{finalsum = !(sum[k])]
}

cout << finalsum ;
return 0;

}

1 个答案:

答案 0 :(得分:2)

看起来你正试图实现TCP的1s补码校验和。

// Compute the sum.  Let overflows accumulate in upper 16 bits.
for(auto j = bitvec.begin(); j != bitvec.end(); ++j) 
    sum += *j;

// Now fold the overflows into the lower 16 bits.  This requires two folds, as the
// first fold may generate another carry.  This can't happen more than once though.
sum = (sum & 0xFFFF) + (sum >> 16);
sum = (sum & 0xFFFF) + (sum >> 16);

// Return the 1s complement sum in finalsum
finalsum = sum;

这应该可以解决问题。

另外,我认为你需要在这个循环的某个地方cp += 2

while (*cp) {
    uint16_t bits = *(cp-1)>>8 + *(cp);
    bitvec.push_back(bits);
    cp += 2;  // advance to next pair of characters
}

如果您的输入字符串不是偶数字符,那么该循环也将失败,因此请考虑更强大地重写它...