Skip to content

Instantly share code, notes, and snippets.

@WhiteBlackGoose
Last active September 3, 2021 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WhiteBlackGoose/ba237742e7cbfd94b34321b78fa69248 to your computer and use it in GitHub Desktop.
Save WhiteBlackGoose/ba237742e7cbfd94b34321b78fa69248 to your computer and use it in GitHub Desktop.
Truncates fractional part of a float
using System;
using System.Runtime.CompilerServices;
public static class Quack
{
public static float GetIntegerPart(float f)
{
var u = Unsafe.As<float, uint>(ref f);
var E = (u << 1) >> (1 + 23);
if (E < 127)
return 0; // negative exponent -> 0
var iE = E - 127;
var ones = uint.MaxValue;
ones = ones - ((1u << (int)(23 - iE + 0)) - 1);
u &= ones;
return Unsafe.As<uint, float>(ref u);
}
public static void Main() {
var r = GetIntegerPart(-2.155f);
Console.WriteLine(r);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment