Get 16 bit floating point precision as a ushort
I saw on SO that using
Convert.ToUInt16(2.2)
would give me the 16 bit representation of the float, but instead it just gives me 2
, what is the proper way to do what i want?31 Replies
Not 100% sure what you want to achieve here
i want 2.2 to be represented as 0x4066
that is the IEEE754 representation
of a 16 bit floating point number
Angius
REPL Result: Success
Result: string
Compile: 495.085ms | Execution: 40.475ms | React with ❌ to remove this embed.
Huh, not quite the expected result
😭
That said... not sure how can you represent a float as an ushort
One has decimal points... another doesn't
maybe i can use a span :p
Unless you do float -> binary -> ushort, to get an ushort value of the binary representation of the float
Which would be... largely pointless, but possible
well the goal is float -> binary string
but a 16 bit binary string
Floats are 32-bit
are there 16 bit floats then?
i mean
like
a "half" type
floats are singles
Not in C#, no
float
is 32 bits, double
is 64, decimal
is 128
Ah, wait
https://devblogs.microsoft.com/dotnet/introducing-the-half-type/
https://learn.microsoft.com/en-us/dotnet/api/system.half?view=net-8.0
Available since .NET 5now i need to figure out a way to convert a float to a half?
You will lose precision doing so
yeah im fine with that
this doesnt seem to work
Well then, look into the
Create
methods
You can't represent a floating point number as an integer
Best case scenario it gets rounded, worst case it gets truncatedoh wait, i think the issue is that ToUInt16 takes in a generic of IConvertable but half doesnt support it
just do
Half h = (Half)2.2f
yeah that works, its the fact that i cant convert it to a ushort
Its 16 bit now, why convert it
i need to write the binary version of it to a file
well
not to a file
to a string
i need to convert a half to a binary string
Do that, then
Where does the
ushort
come in?because i cant directly convert a half to a binary string
Convert.ToString(half, 2);
uh huh
theHalf.ToString("X2")
bool?
thats hex right?
bool is the first overload for ToString, it means there isnt an overload supporting Half
You wanted a hexadecimal string, no?
Half implements IBinaryNumber
Maybe casting it to that will help you
huh?
i dont think x2 can be used on a non-integer type
i found
it works, thanks guys for the brainstorming