-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Set up a helper method for converting fixed-point numbers to doubles.
- Loading branch information
1 parent
c485be4
commit 9ac4350
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
40 changes: 40 additions & 0 deletions
40
Schema/src/binary/reader/BinaryReaderExtensions_FixedPoint.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |