Skip to content

Instantly share code, notes, and snippets.

@fpsunflower
fpsunflower / nanof2a.cpp
Created November 17, 2018 15:24
Tiny float to ascii conversion (with lossless roundtrip, based on the Ryu algorithm)
// c++ -O3 -o nanof2a nanof2a.cpp && ./nanof2a
#include <cstdint>
#include <cstring>
namespace { // anonymous namespace to encourage inlining
struct f2a {
char str[16];
f2a(float f) { // example usage: printf("%s", f2a(f).str)
@fpsunflower
fpsunflower / nanofont.cpp
Created June 3, 2015 07:23
Tiny bitmap font rendering
// c++ -o nanofont nanofont.cpp && time ./nanofont /tmp/font.png && open /tmp/font.png
#include <cstdio>
#include <vector>
// Glyphs from http://font.gohu.org/ (8x14 version, most common ascii characters only)
// Arguments are the ascii character to print, and x and y positions within the glyph.
// This function must be paired with some mechanism to plot pixels (sample below).
inline bool glyph_pixel(unsigned int c, unsigned int x, unsigned int y) {
c -= 33; x--; if (c > 93 || x > 6 || y > 13) return 0; int i = 98 * c + 7 * y + x;
return (("0@P01248@00120000P49B0000000000000:DXlW2UoDX@10008@h;IR4n@R<Y?48000PYDF"
@fpsunflower
fpsunflower / nanopng.cpp
Last active January 31, 2023 19:04
Tiny PNG output
// c++ -o nanopng nanopng.cpp && ./nanopng /tmp/foo.png
#include <cstdio>
// write an uncompressed PNG file from a uint8 RGB buffer
struct Png {
FILE*f; unsigned int tab[256], crc; ~Png() { fclose(f); }
Png(const char* fn, int w, int h, const unsigned char* c) {
crc=0x575e51f5;unsigned char d[]={137,80,78,71,13,
10,26,10,0,0,0,13,73,72,68,82,73,68,65,84,120,1,0,
0,0,73,69,78,68,174,66,96,130};/*chunk headers*/
@fpsunflower
fpsunflower / nanoexr.cpp
Last active December 9, 2021 14:42
Tiny OpenEXR output
// c++ -o nanoexr nanoexr.cpp && ./nanoexr /tmp/foo.exr
#include <cstdio>
// writes a tiled OpenEXR file from a float RGB buffer
struct Exr {
FILE* f; enum{TS=64}; ~Exr() { fclose(f); }
void B(unsigned char i) { fputc(i,f); }
void I(unsigned int i) { fwrite(&i,1,4,f); }
void L(unsigned long long i) { fwrite(&i,1,8,f); }
void F(float x) { fwrite(&x,1,4,f); }