Skip to content

Instantly share code, notes, and snippets.

@ldemailly
Last active May 9, 2025 01:18
Show Gist options
  • Select an option

  • Save ldemailly/45b51186a7999b7eeba04a6639787d2d to your computer and use it in GitHub Desktop.

Select an option

Save ldemailly/45b51186a7999b7eeba04a6639787d2d to your computer and use it in GitHub Desktop.
Magic compression - best ratio ever ;-) 1:442604 for instance on a 22Mb binary to 52bytes !
#!/bin/sh
# Fun idea by https://github.com/ldemailly
set -e
filename="$1"
if [ -z "$filename" ]; then
echo "Usage: $0 <file|file.mc>" >&2
exit 1
fi
get_size() {
# unlike stat should work on both macos and linux
ls -l "$1" | awk '{print $5}'
}
if [ "${filename##*.}" = "mc" ]; then
base="${filename%.mc}"
mv ".$base" "$base"
rm "$filename"
echo "Uncompressed succesfully back to $base"
else
if [ ! -f "$filename" ]; then
echo "File not found: $filename" >&2
exit 1
fi
mv "$filename" ".$filename"
echo "Supercompressed $filename (c) magic compression people" > "$filename.mc"
orig_size=$(get_size ".$filename")
new_size=$(get_size "$filename.mc")
ratio=$(awk "BEGIN {printf \"%.0f\", $orig_size / $new_size}")
echo "Compression ratio: 1:$ratio achieved for $filename -> $filename.mc"
fi
@ldemailly
Copy link
Author

ldemailly commented May 9, 2025

A bit of a private jokes for the fine folks at the Programmer's Hangout discord :)

18:05:00 $ md5sum fortio 
4234f44399b6ff4401ac374548e3f098  fortio

18:05:08 $ ls -lh fortio 
-rwxr-xr-x@ 1 dl  staff    22M May  8 17:55 fortio

18:05:12 $ ./magicompress fortio 
Compression ratio: 1:442604 achieved for fortio -> fortio.mc

18:05:24 $ ls -lh fortio.mc 
-rw-r--r--@ 1 dl  staff    52B May  8 18:05 fortio.mc

18:05:31 $ ls -lh fortio 
ls: fortio: No such file or directory

18:05:42 $ ./magicompress fortio.mc 
Uncompressed succesfully back to fortio

18:05:50 $ ls -lh fortio 
-rwxr-xr-x@ 1 dl  staff    22M May  8 17:55 fortio

18:05:53 $ md5sum fortio 
4234f44399b6ff4401ac374548e3f098  fortio

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