Skip to content

Instantly share code, notes, and snippets.

@kaneta1992
Created January 14, 2019 07:05
Show Gist options
  • Save kaneta1992/f238d71882e93c5c39cc24b285d7e9df to your computer and use it in GitHub Desktop.
Save kaneta1992/f238d71882e93c5c39cc24b285d7e9df to your computer and use it in GitHub Desktop.
vec4 pack(float val) {
// 符号取得
float s = sign(val);
// 絶対値
val *= s;
// 指数取得
float e = floor(log2(val));
// 仮数取得
float m = val / pow(2.0, e);
// vec4にパックする
vec4 packed = vec4((e + 127.0)/256.0, fract((m - 1.0) * vec3(1.0, 256.0, 65536.0)));
// 仮数部は23bitなのでwの1bitに符号を入れる
packed.w = step(s, 0.0) * 0.5 + packed.w * 0.5;
// 256階調にして返す
return floor(packed * 256.0) / 256.0;
}
float unpack(vec4 packed) {
// 指数取得
float e = float(packed.x * 256.0 - 127.0);
// 符号取得
float f = floor(float(packed.w / .5));
float s = sign(f - 0.5);
// 符号部分を消す
packed.w -= f * .5;
// 仮数取得
float m = dot(packed.yzw, vec3(1.0, 1.0/256.0, 1.0/32768.0)) + 1.0;
// 復元
return m * pow(2.0, float(e)) * -s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment