一道搜狗机试题的解答
在网上看到搜狗这道机试题,觉得好深奥。一时技痒,尝试做了下,运行结果比较有意思-“搜狗输入法支持各种炫酷的皮肤,彰显个性的你!!!”。运算涉及到异或、与、(无符号)移位、还有强制转型,难度并不算大。
题目如下:
?
* 搜狗机试题,根据encode方法写出decode方法 * * @author SunShadow * */public class TestDecode {public static void encode(byte[] in, byte[] out, int password) {int len = in.length;int seed = password ^ 0x8c357ca5;for (int i = 0; i < len; ++i) {// 与种子异或后右移5位,即高3位与876位异或 高三位至3-1byte a = (byte) ((in[i] ^ seed) >>> 5);// 与种子的24-17异或后取低五位 低五位至8-4byte b = (byte) (((((int) in[i]) << 16) ^ seed) >>> (16 - 3));a &= 0x7;// 取低三位 00000111b &= 0xf8;// 取高五位11111000out[i] = (byte) (a | b);seed = (seed * 3687989 ^ seed ^ in[i]);}}public static void decode(byte[] in, byte[] out, int password) {int len = in.length;int seed = password ^ 0x8c357ca5;for (int i = 0; i < len; ++i) {int seedForLow3 = seed;int seedForHigh5 = seed >>> 16;byte low3 = (byte) (in[i] << 5); // 现在在8-6位byte hight5 = (byte) (in[i] >>> 3);// 现在在5-1位out[i] = (byte) (((low3 ^ seedForLow3) & 0xe0) | ((hight5 ^ seedForHigh5) & 0x1f));seed = (seed * 3687989 ^ seed ^ out[i]);// 计算种子}}public static void main(String[] args) throws Exception {int password = 0xe87dd9d3;byte[] buf1 = { 29, -16, 96, 43, -85, 25, -96, 83, 13, 66, -109, 49,-111, 0, 60, -101, 99, -86, -38, 86, -35, 48, 23, 83, -102, 25,73, -116, -101, -88, -5, 14, -14, -112, 87, -87, 2, 108, -58,40, 56, 12, 108, 77, 83, 38, 20, -114, };byte[] buf2 = new byte[buf1.length];decode(buf1, buf2, password);System.out.println(new String(buf2, "GBK"));}}??
?