前几天在投递了搜狗Java开发工程师。需要搞一个在线测评,出了一道题目,是程序填空题
要求观察程序,补全decode,输出一句话:
public class Test {
public static void encode(byte[] in, byte[] out, int password)
{
int len = in.length;
int seed = password ^ 0x1963f9c;
for (int i = 0 ; i < len; ++i) {
byte a = (byte)( ( in[i] ^ seed ) >>> 2 );
byte b = (byte)( ( ( ((int)in[i]) << 13 ) ^ seed ) >>> (13-6) );
a &= 0x3f;
b &= 0xc0;
out[i] = (byte)(a | b);
seed = (((seed << 7) ^ seed ^ in[i]) + 5393887);
}
}
public static void decode(byte[] in, byte[] out, int password)
{
int len = in.length;
int seed = password ^ 0x1963f9c;
for (int i = 0 ; i < len; ++i) {
byte a = (byte)(in[i] & 0x3f);
byte b = (byte)(in[i] & 0xc0);
a = (byte)(((a << 2) ^ seed) & 0xfc);
b = (byte)((((((int)b) << (13-6)) ^ seed) >>13) & 0x03);
out[i] = (byte)(a | b);
seed = (((seed << 7) ^ seed ^ out[i]) + 5393887);
}
}
public static void main(String [] args) throws Exception
{
int password = 0x99b90094;
byte[] buf1 = {113, 87, 1, -29, 55, -5, 65, 13, -85, 78, 50, 23, -33, -29, 73, 117, -97, 106, 77, -17, -107, -62, -110, -126, -15, 32, -48, -128, };
byte[] buf2 = new byte[buf1.length];
decode(buf1, buf2, password);
System.out.println(new String(buf2, "GBK"));
}
}
思前想后,发现规律。这就是一系列的移位,我们要做的就是反过来再移一次。先看看encode方法,然后再去实现decode。方法如下:
public static void decode(byte[] in, byte[] out, int password)
{
int len = in.length;
int seed = password ^ 0x1963f9c;
for (int i = 0 ; i < len; ++i) {
byte a = (byte)(in[i] & 0x3f);
byte b = (byte)(in[i] & 0xc0);
a = (byte)(((a << 2) ^ seed) & 0xfc);
b = (byte)((((((int)b) << (13-6)) ^ seed) >>13) & 0x03);
out[i] = (byte)(a | b);
seed = (((seed << 7) ^ seed ^ out[i]) + 5393887);
}
}
最后输出的结果是:听歌从搜狗音乐搜索开始!!!