Skip to content

Instantly share code, notes, and snippets.

@coolgoose85
Last active December 23, 2015 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coolgoose85/458a1f67d61f8def1120 to your computer and use it in GitHub Desktop.
Save coolgoose85/458a1f67d61f8def1120 to your computer and use it in GitHub Desktop.
//Unset range of bits
//For e.g. 1001 1001
//Unset bits from 2 to 5 i.e. 1 0 0 1 1 0 0 1 => 10 0000 01
// |- - - -|
// Bits 7 6 5 4 3 2 1 0
//
//Step1
//------
//To unset range of bits we need to create MASK
// val = 1001 1001
// Mask = 1100 0011 (AND)
// _____________
// 1000 0001
//
//Step 2
//-------
//We need to construct MASK
//In MASK, bits in range are 0 i.e. bits from 2-5 is 0 and
//rest of the bits are 1
// MASK 1 1 0 0 0 0 1 1
// |- - - -|
// Bits 7 6 5 4 3 2 1 0
//
//Step 3
//-------
// 0 0 0 1 1 1 1 1 ((1 << 5) - 1) i.e. (1 << j) - 1
//
//MAX 1 1 1 1 1 1 1 1
// 0 0 1 1 1 1 1 1 (-)
// ------------------
// 1 1 0 0 0 0 0 0 =====> (1)
//
// (1 << 2) - 1 i.e. (1 << i) - 1
// 0 0 0 0 0 1 0 0
// 0 0 0 0 0 0 0 1 (-)
//------------------
// 0 0 0 0 0 0 1 1 =====> (2)
//
// (1) OR (2)
// 1 1 0 0 0 0 0 0
// 0 0 0 0 0 0 1 1 (OR)
//-------------------
// 1 1 0 0 0 0 1 1
//
//Final Step
// val = 1001 1001
// Mask = 1100 0011 (AND)
// _____________
// 1000 0001
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment