I am trying to solve a problem using bit operations in C++ but i am really stuck. Please help me with the following query.
1) Is it possible to create variable’s A and B which take exactly 100000bits in memory and on which an operation like A&B is valid?
2) Is there a fast way to generate B(100000bits) such that its first n bits are 0, last m bits are 0 and the remaining are 1’s? (eg. if B was 10bits then a number like 0000011000)
In answer to 1, sure, this is the sort of things classes were meant for. Simply create a class containing 100,000 bits (about 12.5K) and override the
operator&method (the binary one, not the address-of operator).A good start would be (say we have two integers holding the bitmask):
This is untested but should give you the basic idea. In order to test it, I’d have to code up quite a bit, including constructors, destructors, assignments and so forth, when that really should be your task 🙂
In answer to two, that’s also easy. The only trick bits are the two edge bytes, all the internal bytes can just be set to all 1 bits.
In order to set the edge bytes, you use a bit of division and modulo with the number of bits in a byte and then use bitmasks to set them. The bitmasks would be
0x80,0xc0,0xe0,0xf0,0xf8and so on, with each subsequent value adding another 1 bit.Then you would use
bitmask[bitpos % 8]in its various forms to set the edge bytes, the array indexes of which would bebitpos / 8.