简体   繁体   中英

how to take 1s complement in C++ in the following code?

I want to take a 1s complement of whatever bits are there in sum+ and save the complemented bits in finalsum. how to do that. I am a bit weak with using bitvec and uint32_t type stuff. so i am confused here. please help.

#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;

}

It looks like you're trying to implement something like TCP's 1s complement checksum.

// 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;

This should do the trick.

On a separate note, I think you need a cp += 2 somewhere in this loop:

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

That loop will also fail if your input string isn't an even number of characters, so consider rewriting it more robustly...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM