How to Convert IEEE-754 Floating-Point Conversion From Decimal Floating-Point To 32-bit Hexadecimal ? Example : 75 Decimal Floating-Point = 42960000 hex decimal.
Asked
Active
Viewed 463 times
1
-
How about `string.Join("", BitConverter.GetBytes(75f).Reverse().Select(b => b.ToString("X2")))` ? – Lasse V. Karlsen Nov 10 '21 at 10:46
-
1Does this answer your question? [Converting IEEE 754 float to hex string](https://stackoverflow.com/questions/26064230/converting-ieee-754-float-to-hex-string) – Infosunny Nov 10 '21 at 10:57
-
Or in .Net 5 use `BitConverter.SingleToInt32Bits` – Charlieface Nov 10 '21 at 11:11
-
1@LasseV.Karlsen which is fine until someone uses an other-endian machine (and it is a very expensive way of doing it) – Marc Gravell Nov 10 '21 at 11:27
2 Answers
2
using System;
using System.Buffers.Binary;
float value = 75;
var bytes = new byte[sizeof(float)]; // could also use stackalloc here, but
// would need to do the x2 convert manually
BinaryPrimitives.WriteSingleBigEndian(bytes, value);
var hex = BitConverter.ToString(bytes); // lazy way of getting hex
Console.WriteLine(hex);
You can also use BitConverter
to get the bytes, but then you need to be aware of CPU-endianness:
using System;
float value = 75;
var bytes = BitConverter.GetBytes(value);
if (BitConverter.IsLittleEndian) Array.Reverse(bytes);
var hex = BitConverter.ToString(bytes); // lazy way of getting hex
Console.WriteLine(hex);
or zero-alloc:
using System;
using System.Buffers.Binary;
float value = 75;
Span<byte> bytes = stackalloc byte[sizeof(float)];
BinaryPrimitives.WriteSingleBigEndian(bytes, value);
const string hex = "0123456789abcdef";
foreach (var b in bytes)
{
Console.Write(hex[(b >> 4) & 0b1111]); // hi
Console.Write(hex[b & 0b1111]); // lo
}

Marc Gravell
- 1,026,079
- 266
- 2,566
- 2,900
2
In .Net 5.0+ and .Net Core 2.0+ you can use BitConverter.SingleToInt32Bits
var hex = BitConverter.SingleToInt32Bits(myfloat).ToString("X");
There is also BitConverter.DoubleToInt64Bits
for double

Charlieface
- 52,284
- 6
- 19
- 43