简体   繁体   中英

Bit operation in c++

I want to take bitwise XOR of a number with 4294967295 ie(pow(2,32)-1). Here I am using : number^4294967295 directly. But the result is wrong.So how does this operation takes place. Suggest if any better way to do this.

PS- I am using this technique in https://www.hackerrank.com/challenges/flipping-bits .

Edit1 : result of 1^4294967295 (00000000000000000000000000000001^11111111111111111111111111111111) should be 4294967294 (11111111111111111111111111111110).

Edit2 : Code included :

#include <cmath>
#include <iostream>
using namespace std;
int main() {  
int t;
cin>>t;
int i=31;

while(t--){
    int  var;
    char arr[i];
    int temp = 4294967295;
    cin>>var;
    var= var^temp;
    cout<<var<<endl;

}
return 0;
}

Your code will work correctly with following changes:

  1. int var; --> change to --> unsigned int var;

  2. int temp = 4294967295; --> change to --> unsigned int temp = 4294967295;

signed int has range [−2,147,483,648 to 2,147,483,647]

unsigned int has range [0 to 4,294,967,295]

There's an operator for that. Look at bitwise not in this table .

( live example )

#include <cstdint>
#include <iostream>
#include <iomanip>

int main() {
    uint32_t var;
    std::cin >> std::hex >> var;

    const uint32_t result = ~var;
    std::cout << std::hex << result << "\n";
}

Output (when given 1 as input):

fffffffe

If you insist on doing it your way, you need to use unsigned types. It'll also help to use a fixed-size type (such as uint32_t from <cstdint> ) and to represent your literals in hexadecimal , for convenience ( live example ):

#include <cstdint>
#include <iostream>
#include <iomanip>

int main() {
    const uint32_t mask = 0xffffffff;
    uint32_t var;
    std::cin >> std::hex >> var;

    const uint32_t result = var ^ mask;
    std::cout << std::hex << result << "\n";
}

Output (when given 1 as input):

fffffffe

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