-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBigIntegerExtensions.cs
More file actions
50 lines (42 loc) · 2.02 KB
/
Copy pathBigIntegerExtensions.cs
File metadata and controls
50 lines (42 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
namespace Texnomic.Types.Extensions;
/// <summary>
/// Extension methods for <see cref="BigInteger"/> values.
/// </summary>
public static class BigIntegerExtensions
{
extension(BigInteger Value)
{
/// <summary>Converts the value to a <see cref="BigDecimal"/> with an implicit denominator of one.</summary>
public BigDecimal ToBigDecimal() => new(Value);
/// <summary>Converts the value to a <see cref="BigDecimal"/> scaled by <paramref name="Denominator"/>.</summary>
public BigDecimal ToBigDecimal(BigInteger Denominator) => new(Value, Denominator);
/// <summary>Encodes the value into its minimal unsigned byte representation.</summary>
public byte[] ToBytes(bool IsBigEndian = true)
=> Value.ToByteArray(Value.Sign >= 0, IsBigEndian);
/// <summary>
/// Attempts to encode the value into <paramref name="Destination"/> as unsigned bytes.
/// </summary>
public bool TryWriteBytes(Span<byte> Destination, out int BytesWritten, bool IsBigEndian = true)
=> Value.TryWriteBytes(Destination, out BytesWritten, isUnsigned: Value.Sign >= 0, isBigEndian: IsBigEndian);
/// <summary>Formats the value as a lowercase hexadecimal string with leading zeros stripped.</summary>
public string AsHex(bool Prefixed = true)
{
if (Value.Sign == -1)
{
var Hex = $"{BigInteger.Abs(Value):x}".TrimStart('0');
return Prefixed ? $"0x{Hex}" : Hex;
}
else
{
var Hex = $"{Value:x}".TrimStart('0');
return Prefixed ? $"0x{Hex}" : Hex;
}
}
/// <summary>
/// Formats the value as a fixed-width lowercase hexadecimal string with exactly
/// <c>Width * 2</c> hex characters, left-padded with zero nibbles.
/// </summary>
public string AsPaddedHex(int Width, bool Prefixed = true)
=> Value.ToBytes(IsBigEndian: true).AsPaddedHex(Width, Prefixed);
}
}