Skip to content

Instantly share code, notes, and snippets.

@AtomicVar
Created November 26, 2023 18:03
Show Gist options
  • Save AtomicVar/769d7a96bd06cc720c470f707da3136b to your computer and use it in GitHub Desktop.
Save AtomicVar/769d7a96bd06cc720c470f707da3136b to your computer and use it in GitHub Desktop.
zlib 极简示例:压缩 100 个 float
#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;
}
@AtomicVar
Copy link
Author

示例输出:

Original size: 400
Compressed size: 205
Compressed data: 78 9C 15 D0 31 44 44 01 1C C7 F1 7F 29 E5 52 5E 4A 53 53 D3 4D 4D 4D 2D BD 7A 34 35 35 DD D4 D4 D4 74 53 53 43 71 44 C4 23 22 8E 88 38 22 E2 88 88 47 44 1C 11 71 44 C4 11 11 8F 88 38 EA D3 8F 8F EF FE 8B F8 5F B1 14 91 A6 11 39 05 25 C9 72 44 95 94 1A 75 1A E4 34 69 D1 A6 A0 43 97 1E 25 7D 86 56 22 2A 24 CC 30 CB 1C 55 E6 59 60 91 94 55 D6 58 A7 C6 06 9B 6C 51 67 9B 1D F6 68 B0 CF 01 87 E4 1C 71 CC 09 4D 4E 39 E3 9C 16 17 5C 72 45 9B 6B 6E B8 A5 E0 8E 7B 1E E8 F0 C8 13 CF 74 79 E1 95 37 7A BC F3 C1 27 25 5F 7C F3 43 9F 5F 06 B2 D8 1D CC FC A0 C3 3A A2 A3 5A D1 31 1D D7 09 4D 74 52 A7 74 3A FB 03 33 E8 4F CD

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment