Jenia
Jenia

Reputation:

How to subtract two bitsets in c++

I have 2 bitsets each one storing 100 bits. How to subtract them, treating them as unsigned numbers?

Upvotes: 1

Views: 6473

Answers (3)

navigator
navigator

Reputation: 1596

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

Upvotes: 0

Maciek
Maciek

Reputation: 19893

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.

Upvotes: 1

Arpegius
Arpegius

Reputation: 5887

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;

Upvotes: 10

Related Questions