【发布时间】:2016-06-16 20:26:03
【问题描述】:
您好,我需要计算文件的 m 阶熵,其中 m 是位数 (m
所以:
H_m(X)=-sum_i=0 到 i=2^m-1{(p_i,m)(log_2 (p_i,m))}
所以,我想创建一个输入流来读取文件,然后计算每个由m位组成的序列的概率。
对于 m = 8 这很容易,因为我考虑的是一个字节。 由于 m
无论如何,我无法创建短流。这就是我所做的:
public static void main(String[] args) {
readFile(FILE_NAME_INPUT);
}
public static void readFile(String filename) {
short[] buffer = null;
File a_file = new File(filename);
try {
File file = new File(filename);
FileInputStream fis = new FileInputStream(filename);
DataInputStream dis = new DataInputStream(fis);
int length = (int)file.length() / 2;
buffer = new short[length];
int count = 0;
while(dis.available() > 0 && count < length) {
buffer[count] = dis.readShort();
count++;
}
System.out.println("length=" + length);
System.out.println("count=" + count);
for(int i = 0; i < buffer.length; i++) {
System.out.println("buffer[" + i + "]: " + buffer[i]);
}
fis.close();
}
catch(EOFException eof) {
System.out.println("EOFException: " + eof);
}
catch(FileNotFoundException fe) {
System.out.println("FileNotFoundException: " + fe);
}
catch(IOException ioe) {
System.out.println("IOException: " + ioe);
}
}
但我丢失了一个字节,我认为这不是最好的处理方式。
这就是我认为使用按位运算符要做的事情:
int[] list = new int[l];
foreach n in buffer {
for(int i = 16 - m; i > 0; i-m) {
list.add( (n >> i) & 2^m-1 );
}
}
我假设在这种情况下使用 shorts。 如果我使用字节,我怎样才能为 m > 8 做这样的循环? 该循环不起作用,因为我必须连接多个字节并且每次改变要连接的位数..
有什么想法吗? 谢谢
【问题讨论】:
-
如果你只是计算一个总和,为什么要把每一个值都保存在一个数组中?
-
感谢您的回复。我需要将值保存在数组中,因为我需要获取 m 位的所有子序列,然后计算每个序列的概率。
标签: java inputstream entropy datainputstream