Skip to content

Instantly share code, notes, and snippets.

@siraben
Created April 3, 2026 19:41
Show Gist options
  • Select an option

  • Save siraben/cb0eb96b820a50e11218f0152f2ecc06 to your computer and use it in GitHub Desktop.

Select an option

Save siraben/cb0eb96b820a50e11218f0152f2ecc06 to your computer and use it in GitHub Desktop.
Big-endian testing, reproducibly
#!/usr/bin/env nix-shell
#! nix-shell -i bash --pure
#! nix-shell -p qemu gcc "pkgsCross.mips-linux-gnu.stdenv.cc" "pkgsCross.mips-linux-gnu.stdenv.cc.libc.static" "pkgsCross.s390x.stdenv.cc" "pkgsCross.s390x.stdenv.cc.libc.static"
#! nix-shell -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/ac62194c3917d5f474c1a844b6fd6da2db95077d.tar.gz
# Big-endian testing with QEMU user-mode emulation and Nix cross-compilers.
# Reproduces: https://www.hanshq.net/big-endian-qemu.html
set -euo pipefail
WORKDIR=$(mktemp -d)
trap 'rm -rf "$WORKDIR"' EXIT
cat > "$WORKDIR/endian.c" << 'EOF'
#include <stdint.h>
#include <stdio.h>
int main(void)
{
uint32_t x = 0x12345678;
int i;
for (i = 0; i < sizeof(x); i++) {
printf("mem[%d] = 0x%02x\n", i, ((char*)&x)[i]);
}
return 0;
}
EOF
echo "=== Native (x86_64, little-endian) ==="
gcc -Wl,--no-warn-search-mismatch "$WORKDIR/endian.c" -o "$WORKDIR/endian-native"
"$WORKDIR/endian-native"
echo ""
echo "=== MIPS (big-endian, via qemu-mips) ==="
mips-unknown-linux-gnu-cc -static "$WORKDIR/endian.c" -o "$WORKDIR/endian-mips"
qemu-mips "$WORKDIR/endian-mips"
echo ""
echo "=== s390x (big-endian, via qemu-s390x) ==="
s390x-unknown-linux-gnu-cc -static "$WORKDIR/endian.c" -o "$WORKDIR/endian-s390x"
qemu-s390x "$WORKDIR/endian-s390x"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment