hi ok so i have this scenario:

i have a bitset;

e.g.

` bitset<16> mybitset (string("10000000000000000")) `

where all 16 spaces have been utilized;

for now i just want to use the first 4 elements i.e. 1000. i need a whole number ` 1000 ` and NOT individual numbers ` (1,0,0,0) ` at different index positions
I need a whole number so that i can compare it with other bitsets which already only have 4 elemets. i.e.

` bitset<4> stop (string("0000")); ` ` if(stop== mybitset) ` `{ //do something } `

how do i go about implementing this? kinda new to bitsets
thanks!!
P.S. im working with binary numbers!
Last edited on
You could create a function that starts with a

`int start = 0;`

For every zero, you time start by 10. For every 1 you add 1 AND time by 10:

 ``123456`` ``````int start = 0; for (int i = 0; i < 4; ++i) { start *= 10; start += (mybitset[i] ? 1 : 0); }``````
Last edited on
thanks for your reply! i must be doing something wrong since the value of start ends up to 0 instead of 1000, i dont have any idea why that happens
Bitset is reversing the string that you store. You're not doing anything wrong I think. Try using the flip() function before reading :)
 ``12345678910111213141516`` ``````#include #include #include int main() { const std::bitset<16> mybitset( std::string( "10000000000000000") ) ; const std::bitset<4> stop( std::string( "1000") ) ; if( mybitset.to_string().find( stop.to_string() ) == 0 ) std::cout << "//do something\n" ; // do something // or if( ( mybitset >> 12 ).to_ulong() == stop.to_ulong() ) std::cout << "//do something\n" ; // do something }``````

http://liveworkspace.org/code/xZ21O\$0
flipping doesn't work, if i flip the value is 1111 :(
 ``12`` `````` Why not perform the iteration backwards? Start at the highest element, --i?``````
@JLBorges thanks for your solution, after i modified it a little it works! thanks and thank you also @Bourgond Aries for all your help!

Thanks again :)
Topic archived. No new replies allowed.