Skip to content

Instantly share code, notes, and snippets.

@SH4DY
Created May 31, 2015 19:27
Show Gist options
  • Save SH4DY/1f89dff4a62b02b9a2ab to your computer and use it in GitHub Desktop.
Save SH4DY/1f89dff4a62b02b9a2ab to your computer and use it in GitHub Desktop.
Given an integer n and two indexes i, j s.t. i >= j. return a integer where all the bits between positions i and j (both inclusive) are set to 1. The bits outside of this range shall not be modified.
/*
Given an integer n and two indexes i, j s.t. i >= j.
return a integer where all the bits between positions i and j (both inclusive)
are set to 1. The bits outside of this range shall not be modified.
*/
//Comments assuming 8 bit numbers
//Goal is to make a mask with 1's at positions j through i
public static int setBetween(int n, int i, int j){ //n = 00010000, i = 3, j = 1
int left = (1 << i+1) - 1; // 1 << 4 is 00010000, subtract 1 is 00001111
int right = ~0 << j; //11111111 << 1 is 11111110
int mask = left & right; //00001110
return n | mask;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment