KhronosGroup / KhronosGroup/SPIRV-Cross

generate the smallest float/double that preserves the binary representation

Open
#2,132 2 comments 0 reactions 0 assignees View on GitHub
enhancement maintenance
Dominant language
GLSL
Stars
2.5k
Forks
713
Avg merge
2d 18h
Merged PRs (30d)
16

Description

Currently spirv-cross uses `%.32g` by default to format `floats`, this can be overridden with `SPIRV_CROSS_FLT_FMT` at compile time. When embedding shaders with binaries, reducing their binary footprint can be important.

What really matters is to preserve the binary representation of the float in the SPIRV file. 32 digits is overkill for `floats` and `doubles`. We could use respectively 9 and 17 digits, which is always enough, however, this would still generate strings larger than needed.

Ideally, we'd want to use the smallest string that preserves the binary representation.

For instance, I have tested the following implementation for `floats` only:

```
static inline std::string convert_to_smallest_string(float f, char locale_radix_point) {
char buf[16]; // e.g.: -0.12345678e-12, 16 bytes needed
float r;
for (int i = 1; i < 9; i++) {
sprintf(buf, "%.*g", i, f);
sscanf(buf, "%f", &r);
if (r == f) {
break;
}
}
fixup_radix_point(buf, locale_radix_point);

// Ensure that the literal is float.
if (!strchr(buf, '.') && !strchr(buf, 'e'))
strcat(buf, ".0");

return { buf };
}
```

For `doubles` and `long doubles` it might better to binary-search the right format length.

Contributor guide

No contributing guide indexed for this repository

Research direction

Locate the float-formatting path that uses %.32g and the SPIRV_CROSS_FLT_FMT override; start by checking how generated literals are parsed back to their original values. Define and test what “smallest” means for float, double, and long double while preserving the SPIR-V binary representation, including radix-point and literal-suffix handling.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
32/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.