Skip to content

Commit

Permalink
Set up a helper method for converting fixed-point numbers to doubles.
Browse files Browse the repository at this point in the history
  • Loading branch information
MeltyPlayer committed Dec 1, 2024
1 parent c485be4 commit 9ac4350
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions Schema/src/binary/reader/BinaryReaderExtensions_FixedPoint.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System;

using schema.util;

namespace schema.binary;

public static partial class BinaryReaderExtensions {
/// <summary>
/// Shamelessly stolen from:
/// https://github.com/scurest/apicula/blob/3d4e91e14045392a49c89e86dab8cb936225588c/src/util/fixed.rs#L5-L35
/// </summary>
public static double ReadDoubleFixedPoint(this IBinaryReader br,
byte signBits,
byte integerBits,
byte fractionBits) {
var totalBits = (uint) (signBits + integerBits + fractionBits);
var totalBytes = (int) BitLogic.BytesNeededToContainBits(totalBits);

var value = totalBytes switch {
1 => br.ReadByte(),
2 => br.ReadUInt16(),
3 => br.ReadUInt24(),
4 => br.ReadUInt32(),
};

double doubleValue;
if (signBits == 0) {
doubleValue = value;
} else {
var signMask = 1 << (integerBits + fractionBits);
if ((value & signMask) != 0) {
doubleValue = (double) (value | ~(signMask - 1));
} else {
doubleValue = value;
}
}

return doubleValue * Math.Pow(.5, fractionBits);
}
}

0 comments on commit 9ac4350

Please sign in to comment.