Skip to content

Instantly share code, notes, and snippets.

@nsivabalan
Created November 2, 2013 18:41
Show Gist options
  • Save nsivabalan/7282110 to your computer and use it in GitHub Desktop.
Save nsivabalan/7282110 to your computer and use it in GitHub Desktop.
public class FindSetBits {
public static int getTotalSetBits(byte[] b, int offset, int endIndex)
{
int size = b.length;
length = endIndex - offset;
if(offset > size*8) throw new IllegalArgumentException("Offset overflow");
if((offset + length )> size*8) throw new IllegalArgumentException("Offset overflow");
int startIndex = offset;
int remLength = length;
int totalBits = 0;
while(startIndex < (offset+ length))
{
int byteIndex = startIndex/8;
if(remLength >= 8 )
{
int len = 8 - startIndex%8;
totalBits += getNumSetBits(b[byteIndex], startIndex%8, len);
remLength -= len;
startIndex += len;
}
else{
totalBits += getNumSetBits(b[byteIndex], startIndex%8, remLength);
break;
}
}
return totalBits;
}
private static int getNumSetBits(byte b, int offset, int length)
{
if(offset + length > 8) throw new IllegalArgumentException("Length cannot exceed byte length ");
int num = 0;
for(int i = offset;i<=(offset+length); i++)
{
if( ((int)b&(1<<(8-i-1))) > 0)
num++;
}
return num;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment