Hello.
I am coding a dynamic solution to a problem with buttons.
a button can be on or off. there are n buttons
so i thought of trying all possibilities of bits(1 or 0) of length n
for example for n=3
000
001
010
011
100
110
111
do you have any idea how i can iterate through all these for any n?
Thanks
its not just about this problem. i actually get this idea on many problems. but i never knew how to do it so i did something else. this is just an example.
In case than you need an integer that represent what buttons are down and what are up, you can compute the number:
int i = a[0]*1 + a[1]*2 + a[2]*4 + a[3]*8 +...
This number is unique for every image of up-down buttons
the problem is to get the array a ;p i did what you said but it's impractical so i asked here to see if there is anything easier(with bitsets for example)
interate through each number from 0 to (2^n)-1, and at each iteration use the bit shift operator << and then AND that bit with 1 to print out whether or not a 1 or 0 is in that location.
in this manner you can have someone input a value for n and it will give you all the possible iterations. Though you can clearly see youll have 2^n iterations no matter what n you give
Is 8 bits that can represent numbers form 0 to 255 with all posible compinations. Like 0-999 in normal numbers basis 10 represents 1,000 numbers with 3 decimal "bits"
That's why you're not understanding me. The C++ Standard formally states that the amount of bits "char" must represent is 8 at minimum (2^{8}). Therefore, any number of bits per byte is to be assumed. While 8 is usually the normal amount of bits that form a byte, this cannot be assumed as in some cases, this is purely implementation specific.
All that means is that a "char" is a minimum of 8 bits. This does not mean that any number of bits to a byte can be assumed.. it still holds true that 8 bits is a byte.. youre getting confused.. a char is not explicitly a byte, nor vice versa. So on one system say a char is made up of 12 bits. This does NOT mean that there are 12 bits to a byte.
All that means is that a "char" is a minimum of 8 bits.
standard wrote:
1.7 The C++ memory model [intro.memory]
The fundamental storage unit in the C++ memory model is the byte. A byte is at least large enough to contain any member of the basic execution character set (2.3) and the eight-bit code units of the Unicode UTF-8 encoding form and is composed of a contiguous sequence of bits, the number of which is implementation defined.