Justin Taft - Home / Posts

Encoding arbitrary values as floats

I came across an interesting stack overflow that took input from scanf(“%lf”), and stored it into a buffer.
Due to precision, you can’t simply encode an arbitrary unsigned integer into a float through decimal representation.

Reading the source code of scanf, I came across an alternative encoding known as hex float. This encoding appeared to be accepted by libc’s %lf format for scanf too.

$ cat test.c && gcc test.c && ./a.out 
#include <stdio.h>
int main() {
    unsigned long value = 0x4141414141414141;
    printf("%la\n",*(double *)&value);
}

https://en.cppreference.com/w/cpp/language/floating_literal
0x1.1414141414141p+21

Leave a Reply

Your email address will not be published. Required fields are marked *