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!

C#

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.

C#

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:

C#

int set8bits (int value) { // set high bits int bit= 128; for ( int i=7, i>=0, i--) { if (value & bit) { // is true when bit is already set break; } value = value | bit; // set bit bit= bit >> 1 // move next bit } return value; }