Yes, you can calculate this by simply taking the number in question and using bit shifts to determine power 2.
The right offset takes all the bits in the number and moves them to the right, discarding the rightmost (least significant) digit. This is equivalent to doing an integer division by 2. Left shift of the value moves all the bits to the left, discarding bits that are shifted from the left end, and adds zeros to the right end, effectively multiplying the value by 2. Therefore, if you count how many times you need to shift to the right before the number reaches zero, you calculated the integer part of the logarithm of base 2. Then use it to create the result by shifting the value 1 so many times.
int CalculateK(int val) { int cnt = 0; while(val > 0) { cnt++; val = val >> 1; } return 1 << cnt; }
EDIT: Alternatively, and a little easier: you do not need to calculate the counter
int CalculateK(int val) { int res = 1; while(res <= val) res <<= 1; return res ; }
source share