Your code to set bits look rather complicated.
First of all you need to know that an integer is stored in base 2, the integer is a field of bits.
example of 10!
10= 1*2^3+0*2^2+1*2^1+0*2^0
bits are numbered from right to left, starting with bit 0 and number match the powers of 2 from previous formula.
bit numbers: 7 6 5 4 3 2 1 0
Values: ^ = 1 = 2^0
^ = 2 = 2^1
^ = 4 = 2^2
^ = 8 = 2^3
...
^ = 128 = 2^7
10 is 0 0 0 0 1 0 1 0
To set high bits in the 8 bits, you just have to use the knowledge of their values and know bitwise operations.
a single loop does the trick:
int set8bits (int value) {
int bit= 128;
for ( int i=7, i>=0, i--) {
if (value & bit) {
break;
}
value = value | bit;
bit= bit >> 1
}
return value;
}