Skip to content

Commit 0ee1694

Browse files
committed
Add BinaryPrimitivesCompat methods for float32 little-endian serialization
Signed-off-by: Medha Tiwari <[email protected]>
1 parent 2c4a16a commit 0ee1694

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/MongoDB.Bson/IO/BinaryPrimitivesCompat.cs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,5 +31,35 @@ public static void WriteDoubleLittleEndian(Span<byte> destination, double value)
3131
{
3232
BinaryPrimitives.WriteInt64LittleEndian(destination, BitConverter.DoubleToInt64Bits(value));
3333
}
34+
public static float ReadSingleLittleEndian(ReadOnlySpan<byte> source)
35+
{
36+
if (source.Length < 4)
37+
{
38+
throw new ArgumentOutOfRangeException(nameof(source), "Source span is too small to contain a float.");
39+
}
40+
41+
int intValue =
42+
source[0] |
43+
(source[1] << 8) |
44+
(source[2] << 16) |
45+
(source[3] << 24);
46+
47+
return BitConverter.Int32BitsToSingle(intValue);
48+
}
49+
50+
public static void WriteSingleLittleEndian(Span<byte> destination, float value)
51+
{
52+
if (destination.Length < 4)
53+
{
54+
throw new ArgumentOutOfRangeException(nameof(destination), "Destination span is too small to hold a float.");
55+
}
56+
57+
int intValue = BitConverter.SingleToInt32Bits(value);
58+
destination[0] = (byte)(intValue);
59+
destination[1] = (byte)(intValue >> 8);
60+
destination[2] = (byte)(intValue >> 16);
61+
destination[3] = (byte)(intValue >> 24);
62+
}
63+
3464
}
3565
}

0 commit comments

Comments
 (0)