Created
November 26, 2023 18:03
-
-
Save ZJUGuoShuai/769d7a96bd06cc720c470f707da3136b to your computer and use it in GitHub Desktop.
zlib 极简示例:压缩 100 个 float
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <zlib.h> | |
#define BUFFER_SIZE 100 | |
int main() { | |
float buffer[BUFFER_SIZE]; // Assuming you have a buffer of 100 floats | |
// Fill the buffer with some data (for demonstration purposes) | |
for (int i = 0; i < BUFFER_SIZE; i++) { | |
buffer[i] = i * 1.5; | |
} | |
// Convert the buffer to a byte array | |
const void* inputBuffer = (const void*)buffer; | |
size_t inputSize = sizeof(float) * BUFFER_SIZE; | |
// Create an output buffer to store the compressed data | |
Bytef* compressedBuffer = (Bytef*)malloc(sizeof(Bytef) * inputSize); | |
// Initialize zlib stream | |
z_stream stream; | |
stream.zalloc = Z_NULL; | |
stream.zfree = Z_NULL; | |
stream.opaque = Z_NULL; | |
stream.avail_in = (uInt)inputSize; | |
stream.next_in = (Bytef*)inputBuffer; | |
stream.avail_out = (uInt)inputSize; | |
stream.next_out = compressedBuffer; | |
// Initialize deflate compression | |
if (deflateInit(&stream, Z_DEFAULT_COMPRESSION) != Z_OK) { | |
fprintf(stderr, "Failed to initialize deflate compression.\n"); | |
return 1; | |
} | |
// Compress the data | |
if (deflate(&stream, Z_FINISH) != Z_STREAM_END) { | |
fprintf(stderr, "Failed to compress the data.\n"); | |
deflateEnd(&stream); // Clean up | |
return 1; | |
} | |
// Get the compressed data size | |
size_t compressedSize = stream.total_out; | |
printf("Original size: %zu\n", inputSize); | |
printf("Compressed size: %zu\n", compressedSize); | |
// Clean up the zlib stream | |
deflateEnd(&stream); | |
// Print the compressed data | |
printf("Compressed data: "); | |
for (size_t i = 0; i < compressedSize; i++) { | |
printf("%02X ", compressedBuffer[i]); | |
} | |
printf("\n"); | |
// Clean up the compressed buffer | |
free(compressedBuffer); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
示例输出: