# counting bits in byte array in Java

• April 20th, 2002, 04:00 PM
nancen
counting bits in byte array in Java
Hi,I am currently working on a program to count bits in a byte array with 8 elements in Java. that is actually 64 bits in total.
Of course,I can cast each individual byte to integer,then keeping divide it by 2,get the remainder,until quotient is zero,just
count remainder if remainder is 1.I think it is too messy,is there an easy and efficient way ?

nancen
• April 20th, 2002, 04:18 PM
hot_ice
Hi, I'm sorry, but I don't exactly know what you mean. I'm kinda thinking something, but not sure if it's your problem. Could you just explain it again...more clearer? Maybe it's just me, but I need good explanations, otherwise, I dunno what's going on.

:)

Also, if you got the source code, can you attach it, it would help if I could see it - I could understand what you are trying to get at more.

Greg
• April 21st, 2002, 01:57 PM
nancen
Hi,Greg,

Sorry for confusion.Since it is part of a program. However,I could explain in the following way:
I got a byte array: byte cryptogram[8];
The value is given: cryptogram[0]= 00011010;(Actually I couldn't find syntax like this in Java,
just assume it is a byte with value "00011010").
cryptogram[1]=00110110;
.........
cryptogram[7]=00110101;
Now what I was asked to do is count how many '1' in this byte array.
So : cryptogram[0] has three '1', cryptogram[1] has four '1',etc,then add
3+4+....+4;
This is part of program to study diffusion property of an encryption algorithm called OMEA.
The only way I could think about is:
int a,count=0;
for(int i=0;i<8;i++)
{
a=(int)cryptogram[i];
while( a!=0)
{
if(a%2==1)
count++;
a=a/2;
}
}
I found it is a bit messy,I was thinking to use one of bit operation,to get out number of 1 's in one go.Could you help me with that ?

Thanks and regards.

nancen
• April 21st, 2002, 02:16 PM
slarty
The way you're doing it is probably close to the best anyway, the only thing is, I'd use the logical "and" operator and logical "shift" operators instead of dividing by 2 and modulo 2

They probably aren't any more efficient but are logically "closer" to what you want to do

int countBits(byte b)
{
int c=0;
while (b != 0) {
if (( b & 1) != 0) c++;
b = b >> 1;
}
return c;
}

Or something
Or maybe even

int countBits(byte b)
{
int c=0;
while (b != 0) {
c += (b & 1);
b = b >> 1;
}
return c;
}
• April 21st, 2002, 02:51 PM
nancen
Thanks,I think it is better, bit operation is always faster than others.

nancen