Java Deflater等效于Javascript

时间:2016-08-05 01:56:20

标签: javascript java

我正在尝试使用需要压缩邮件的Web服务。当前的实现是在Java中完成的,但是,我想将它移植到Javascript。压缩的工作原理如下:

String params = "hello";

byte[] bytes = params.getBytes();

ByteArrayOutputStream bao = new ByteArrayOutputStream(bytes.length);    
byte[] buffer = new byte[1024];
byte[] out = null;
int len;

Deflater compress = new Deflater();
compress.setInput(bytes);
compress.finish();
while(!compress.finished()) {
     len = compress.deflate(buffer);
     bao.write(buffer, 0, len);
}
out = bao.toByteArray(); 

//Output: [120, -100, -53, 72, -51, -55, -55, 7, 0, 6, 44, 2, 21]

我尝试使用各种inflate / deflate库,例如type definition / Zlib,但没有取得任何成功:

function stringToUint(string) {
    var charList = string.split(''),
    uintArray = [];
    for (var i = 0; i < charList.length; i++) {
        uintArray.push(charList[i].charCodeAt(0));
    }
    return new Uint8Array(uintArray);
}  

var bytes = stringToUint('hello'); 
var compressed = pako.deflate(bytes); 

//Output: [120, 156, 203, 72, 205, 201, 201, 7, 0, 6, 44, 2, 21]

比较输出:

Java Output: [120, -100, -53, 72, -51, -55, -55, 7, 0, 6, 44, 2, 21]
JS   Output: [120,  156, 203, 72, 205, 201, 201, 7, 0, 6, 44, 2, 21]

1 个答案:

答案 0 :(得分:0)

感谢大家的帮助,看起来字节数据是相同的,我只需要将它转换为有符号数组。