If I have an input, say 51 (00110011) and an index i representing a bit index (ex. i = 0 -> 1, i = 2 -> 0), how to I find a power of 2 like these examples. Sorry, I'm not great with math notation but I can give sample input and output.
Example: If given 51 and index 1 (00110011), I want a function to return 00010000 = 16.
Also, if given 173 and index 2 (10101101), the function must return 00001000 = 8.
I'm looking for a solution that uses bit operations and no loops based on the size of the number preferably.
EDIT: This isn't homework. I'm writing a program that stores user selections as a number. I'm trying to challenge myself here.
Here is what little I've been able to do
x--;
for (int j = 0; j < 5; j++) {
x |= x >> (int) Math.pow(2, i);
}
x++;
return x;
This takes a 32 bit number and returns the next power of 2. I'm not sure if this is of any use though to my problem. I tried seeing if anyone else had posted something similar and this is what I found and thought it might play in to what I'm trying to do.
EDIT 2 I'm having users select days of the week and store those days in a single number. Given a day, I want to find the next day the user has selected. I can easily do that by converting the number to a boolean array but wanted to see if there were any other clever solutions out there. I apologize if it's too "homework" like.
I've realize if I take a number like 51 (00110011) and index 1, I can shave off the first two bits by dividing by 2^1 = 001100. Then, I want the program to find the position of the first 1 (index 2). Then it should return 2^(2+2) because it shaved off 2 bits and the next logical 1 was at index 2 after that.