1

How to Convert IEEE-754 Floating-Point Conversion From Decimal Floating-Point To 32-bit Hexadecimal ? Example : 75 Decimal Floating-Point = 42960000 hex decimal.

Ooi
  • 31
  • 5

2 Answers2

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
  • 976,458
  • 251
  • 2,474
  • 2,830
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
  • 29,562
  • 5
  • 12
  • 30