所以我在這裏做普林斯頓的一個練習: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);
}
}
你爲什麼要把所有東西都轉換成字符串呢?您可以直接在int上使用java xor運算符,並將代碼大小縮小一半。 – toto2 2011-05-31 15:08:52