Java 逐位运算
我正在做一个类项目,是哈夫曼算法。读取文件并生成哈夫曼代码(1s&0s)后,我必须使用逐位操作将其导出到新文件。出于某种原因,当我使用逐位操作导出文件时,文件会比以前更大。对于表示前面字符的1和0字符串,使用按位方式,我必须将每个1和0保存在8位的链中。这是我的代码:Java 逐位运算,java,bit-manipulation,Java,Bit Manipulation,我正在做一个类项目,是哈夫曼算法。读取文件并生成哈夫曼代码(1s&0s)后,我必须使用逐位操作将其导出到新文件。出于某种原因,当我使用逐位操作导出文件时,文件会比以前更大。对于表示前面字符的1和0字符串,使用按位方式,我必须将每个1和0保存在8位的链中。这是我的代码: byte currentByte = 0; for (int i = 0, j = 0; i < binaryString.length(); i++, j++) { if (binaryString.charAt(
byte currentByte = 0;
for (int i = 0, j = 0; i < binaryString.length(); i++, j++) {
if (binaryString.charAt(i) == '1') {
currentByte |= (byte) Math.pow(2, 7 - j);
}
if (i != 0 && (i % 8 == 0 || i == binaryString.length() - 1)) {
output.writeObject(currentByte);
if (i % 8 == 0) {
currentByte = 0;
j = 0;
}
}
}
byte currentByte=0;
对于(int i=0,j=0;i
谢谢。您使用的是
ObjectOutputStream
,它用于Java对象的可移植序列化。如果要写入单个字节,则应使用文件输出流
。问题是您使用的是writeObject方法,而不是write方法
writeObject方法写入有关对象以及对象本身的信息,其中write方法设计为只写入单个字节
您还应该使用而不是
请参阅:公共静态void main(字符串[]args)引发IOException
{
FileOutputStream输出=新的FileOutputStream(“C:\\temp\\t.dat”);
字符串inp=“110000110011”;
字节[]ar=新字节[1];
int b=0;
int j=0;
int i=0;
而(i b |=1为什么一开始就要生成一个由1和0组成的字符串?这是一个无用的额外步骤,只需要额外的时间
通常的方法是使用一个方便位数的“缓冲区”(比如32位,因为这是一个int
),为编码的每个符号向该缓冲区写入一个可变位数的位,并从缓冲区中取出整个字节
例如,(未测试,但我以前做过)
int buffer=0,bufbits=0;
对于(int i=0;i 缓冲区如果
位置:
public static void main(String[] args) {
String binaryString = "1111111100000010";
byte currentByte = 0;
for (int i = 0, j = 0; i < binaryString.length(); i++, j++) {
if (i != 0 && i % 8 == 0 || i == binaryString.length() - 1) {
System.out.println(currentByte); // for debug
currentByte = 0;
j = 0;
}
if (binaryString.charAt(i) == '1') {
currentByte |= 1 << 7 - j;
}
}
}
请注意,如果您有11111111
,则这是byte
类型中的-1
int buffer = 0, bufbits = 0;
for (int i = 0; i < symbols.length(); i++)
{
int s = symbols[i];
buffer <<= lengths[s]; // make room for the bits
bufbits += lengths[s]; // buffer got longer
buffer |= values[s]; // put in the bits corresponding to the symbol
while (bufbits >= 8) // as long as there is at least a byte in the buffer
{
bufbits -= 8; // forget it's there
stream.write((byte)(buffer >>> bufbits)); // and save it
// note: bits are not removed from the buffer, just forgotten about
// so it will "overflow", but that is harmless.
// you will see weird values in the debugger though
}
}
public static void main(String[] args) {
String binaryString = "1111111100000010";
byte currentByte = 0;
for (int i = 0, j = 0; i < binaryString.length(); i++, j++) {
if (i != 0 && i % 8 == 0 || i == binaryString.length() - 1) {
System.out.println(currentByte); // for debug
currentByte = 0;
j = 0;
}
if (binaryString.charAt(i) == '1') {
currentByte |= 1 << 7 - j;
}
}
}
1
2