tags:

views:

375

answers:

3

Hi,

i have 2 bitsets each one storing 100 bits. I'm trying to simply subtract with '-', but I always get a compilation error at this point. How do you subtract 2 bitsets in c++?

Thanks in advance

+6  A: 

If you mean to clear all bits in first operand witch are sets in other one, you need to make a binnary and with negated second operand:

std::bitset<10> first (string("1001001001"));
std::bitset<10> second (string("1001000000"));

cout << (first & ~second) << endl;
lionbest
It would be worth noted that this solution isn't *substracting*. It might be more meaningful in a bitset context than mere substraction, but as Neil asked you can never know the real intend.
Steve Schnepp
I think this guess is right, but if what is wanted is bitwise modulo subtraction, then that's the same thing as bitwise addition: XOR. So `first ^ second`. 0 - 1 = 1, 1 - 0 = 1, 1 - 1 = 0, 0 - 0 = 0.
Steve Jessop
+1  A: 

I'm assuming that you're referring to a 128-bit integer number, and are attempting to subtract 2 128bit ints. I'd recommend googling for BigNum - a library which is designed to handle LARGE numbers. The functionality you're after is probably already implemented.

Maciek
A: 

convert both bitsets to unsigned long, using the to ulong (unsigned long) method of std::bitset, subtract the unsigned longs then use the subtraction result construct a new bitset from the result.

#include <bitset>
#include <iostream>

int main( )
{

   std::bitset<10> b1 ( 77 );
   std::bitset<10> b2 ( 55 );

   unsigned long diff = b1.to_ulong() - b2.to_ulong();
   std::bitset<10> result( diff );
   std::cout << diff << std::endl;
   std::cout << result << std::endl;
   return 0;
}
navigator
He said the bitsets were of size 100, not 10.
anon
I was just giving an example.
navigator
How does he scale up from 10 to 100? The example as it stands is worthless.
anon
don't think this is gonna work mate
Maciek
urgh, you're right my bad...
navigator