所以我在这里做普林斯顿大学的一项练习:http ://www.cs.princeton.edu/courses/archive/fall10/cos126/assignments/lfsr.html
,我已经用 LFSR 类的数据进行了全面测试已经提供了,所以我确定我在那里没有出错。但是,我的 PhotoMagic 类会生成管道的加密照片,如下所示:
这不是它应该出现的样子。知道我的代码哪里出错了吗?
import java.awt.Color;
public class PhotoMagic
{
private LFSR lfsr;
public static void main(String args[])
{
new PhotoMagic("src/pictures/shield.png","01101000010100010000",16);
}
public PhotoMagic(String imageName,String binaryPassword,int tap)
{
Picture pic = new Picture(imageName);
lfsr = new LFSR(binaryPassword,tap);
for (int x = 0; x < pic.width(); x++)
{
for (int y = 0; y < pic.height(); y++)
{
Color color = pic.get(x, y);
int red = color.getRed();
int blue = color.getBlue();
int green = color.getGreen();
int transparency = color.getTransparency();
int alpha = color.getAlpha();
int newRed = xor(Integer.toBinaryString(red),paddedBitPattern(lfsr.generate(8)));
int newGreen = xor(Integer.toBinaryString(green),paddedBitPattern(lfsr.generate(8)));
int newBlue = xor(Integer.toBinaryString(blue),paddedBitPattern(lfsr.generate(8)));
Color newColor = new Color(newRed, newGreen, newBlue);
pic.set(x, y, newColor);
}
}
pic.show();
}
/**
* Pads bit pattern to the left with 0s if it is not 8 bits long
* @param bitPattern
* @return
*/
public String paddedBitPattern(int bitPattern)
{
String tempBit = Integer.toBinaryString(bitPattern);
String newPattern = "";
for(int i = 1; i < 9-tempBit.length(); i++)
{
newPattern += "0";
}
newPattern += tempBit;
return newPattern;
}
/**
* Performs the bitwise XOR
* @param colorComponent
* @param generatedBit
* @return
*/
public int xor(String colorComponent, String generatedBit)
{
String newColor = "";
for(int i = 0; i < colorComponent.length(); i++)
{
if(colorComponent.charAt(i) != generatedBit.charAt(i))
{
newColor += 1;
}
else
{
newColor += 0;
}
}
return Integer.valueOf(newColor,2);
}
}