Last active
September 3, 2021 09:09
-
-
Save WhiteBlackGoose/ba237742e7cbfd94b34321b78fa69248 to your computer and use it in GitHub Desktop.
Truncates fractional part of a float
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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