0

I've been using the bitset the following way:

unsigned long value = 0;
bitset<size> myBitset(value);
// do something with the bitset
value = myBitset.to_ulong();

Is there a way to avoid using the last line and affect the value's bits from the bitset directly?

Dan
  • 59
  • 7
  • Perhaps you could show us the kind of code you'd hope to be able to write? My guess is that you're envisaging something like `bitset_reference myBitsetRef(value);` then being able to do things to `myBitsetRef` that directly affect `value`; if so, then no - there's no existing facility in the C++ Standard Library to do that. You'd have to write your own. But, why would you want to? Calling `myBitset.to_ulong()` might seem like an extra step you could eliminate, but the optmiser's probably onto that already. Use, compile with optimisation, inspect the generated code.... – Tony Delroy Apr 15 '18 at 11:10
  • 1
    What is the purpose of the code? What are you going to do with the bits in the bitset after this code? What are you doing with the bitset in the "do something" section you don't show us? Can't you operate on the bits directly using bitwise operators on `value`? – Some programmer dude Apr 15 '18 at 11:11
  • Then why bitset? – con ko Apr 15 '18 at 11:14
  • @Someprogrammerdude Yes, I also think so, there is no need to use bitset **here**. – con ko Apr 15 '18 at 11:17
  • I m constrained to work with a global variable called "value" inside a function and that variable needs to be updated every time the function ends. Also I need to write the less amount of code that I can. I'm allowed to use the bitset library but no other custom library. So I found that the bitset could prove to be the best option to write less code (without using bitwise operators). Inside the "do something block" could be any method call from the bitset class or anything that would affect the bitset. – Dan Apr 15 '18 at 11:23
  • What I wanted to achieve was to do something like @TonyDelroy described. Unfortunately, it seems that this is not possible just from the C++ Standard Library. – Dan Apr 15 '18 at 11:27
  • You could try assigning `value` a raw pointer to the memory address of the bitset. Not sure if it will work though. – KonaeAkira Apr 15 '18 at 14:05
  • 1
    @KonaeAkira: so `unsigned long* value = (cast)&myBitset`? It'd constitute aliasing, and have behaviour undefined in the C++ Standard, but some compilers (e.g. GCC) have modes ("no strict aliasing") where the behaviour's safe. Still, you'd have to check the the bitset and pointed-to-type were of the same size, and I don't *think* you'd have any guarantee about the ordering of the bits in the bitset (i.e. the "0" bit in the bitset might not be the least significant bit in the integral value) - could check the Standard carefully if you were going to try that and wanted to assess portability. – Tony Delroy Apr 16 '18 at 11:50

0 Answers0