美文网首页
lz4解压缩

lz4解压缩

作者: 水煮杰尼龟 | 来源:发表于2023-02-25 15:47 被阅读0次

    最近项目用到了lz4解压缩,简单记录一下

    iOS

    + (NSData *)deCompressToData:(NSString *)str size:(size_t)destsize {
        NSData *d = [self convertHexStrToData:str];
        size_t destSize = destsize;
        uint8_t *destBuf = malloc(sizeof(uint8_t) * destSize);
        const uint8_t *src_buffer = (const uint8_t *)[d bytes];
        size_t src_size = d.length;
        ///lz4 解压
        size_t decompressedSize = compression_decode_buffer(destBuf, destSize, src_buffer, src_size,
                                                                NULL, COMPRESSION_LZ4_RAW);
        NSData *adata = [[NSData alloc]initWithBytes:destBuf length:destSize];
        
        return adata;
    }
    //将16进制的字符串转换成NSData
    + (NSData *)convertHexStrToData:(NSString *)str {
        if (!str || [str length] == 0) {
            return nil;
        }
        
        NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
        NSRange range;
        if ([str length] %2 == 0) {
            range = NSMakeRange(0,2);
        } else {
            range = NSMakeRange(0,1);
        }
        for (NSInteger i = range.location; i < [str length]; i += 2) {
            unsigned int anInt;
            NSString *hexCharStr = [str substringWithRange:range];
            NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
            
            [scanner scanHexInt:&anInt];
            NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
            [hexData appendData:entity];
            
            range.location += range.length;
            range.length = 2;
        }
        
        return [hexData copy];
    }
    

    安卓

    /**
         * 数据解压缩
         * @param data 数据
         * @return
         * @throws IOException
         */
        @Throws(IOException::class)
        fun deCompress(data: ByteArray): ByteArray? {
            var data = data
            val bais = ByteArrayInputStream(data)
            val baos = ByteArrayOutputStream()
    
            // 解压缩
            deCompress(bais, baos)
            data = baos.toByteArray()
            baos.flush()
            baos.close()
            bais.close()
            return data
        }
    
    /**
         * 解压缩
         * @param is 输入流
         * @param os 输出流
         * @throws IOException
         */
        @Throws(IOException::class)
        private fun deCompress(`is`: InputStream, os: OutputStream) {
            val bcis = BlockLZ4CompressorInputStream(`is`)
            var count: Int
            val data = ByteArray(BUFFER)
            while (bcis.read(data, 0, BUFFER).also { count = it } != -1) {
                os.write(data, 0, count)
            }
            bcis.close()
        }
    

    我这边是构建原生插件给到flutter这边使用的,可自行入参调整一下方法。

    相关文章

      网友评论

          本文标题:lz4解压缩

          本文链接:https://www.haomeiwen.com/subject/wyifldtx.html