Skip to content

Instantly share code, notes, and snippets.

@mbcrawfo
Created January 22, 2015 05:22
Show Gist options
  • Save mbcrawfo/ea2c0a7c5306a854533b to your computer and use it in GitHub Desktop.
Save mbcrawfo/ea2c0a7c5306a854533b to your computer and use it in GitHub Desktop.
Counts the number of "1" bits in a file.
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.text.MessageFormat;
import javax.swing.JFileChooser;
public class BitCount {
public static void main(String[] args) {
while (true) {
JFileChooser chooser = new JFileChooser();
int retVal = chooser.showOpenDialog(null);
if (retVal == JFileChooser.CANCEL_OPTION) {
break;
}
File file = chooser.getSelectedFile();
long length = file.length();
System.out.println("File: " + file.getName());
System.out.println(MessageFormat.format("Reading {0} bytes", length));
byte[] buffer = new byte[4];
long count = 0;
try {
InputStream input = new BufferedInputStream(new FileInputStream(file));
while (input.read(buffer) > 0) {
int i = ByteBuffer.wrap(buffer).getInt();
count += Integer.bitCount(i);
}
long totalBits = length * 8;
double percentage = ((double)count / (double)totalBits);
System.out.println(MessageFormat.format(
"Counted {0} 1s out of {1} bits ({2,number,#.##%})",
count, totalBits, percentage
));
}
catch (Exception ex) {
System.out.println("Error");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment