sockscape/server/Libraries/Square/NumericExtensions.cs

75 lines
2.5 KiB
C#
Raw Normal View History

2017-05-08 21:06:17 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
2017-05-17 21:06:16 +00:00
using System.Numerics;
using System.Globalization;
2017-05-08 21:06:17 +00:00
namespace Square {
public static class NumericExtensions {
2017-05-09 21:08:39 +00:00
public static byte[] Pack(this Single value) {
return BitConverter.GetBytes(value).HostToNetworkOrder();
}
2017-05-08 21:06:17 +00:00
2017-05-09 21:08:39 +00:00
public static byte[] Pack(this Double value) {
return BitConverter.GetBytes(value).HostToNetworkOrder();
}
public static byte[] Pack(this Int16 value) {
return BitConverter.GetBytes(value).HostToNetworkOrder();
}
public static byte[] Pack(this UInt16 value) {
return BitConverter.GetBytes(value).HostToNetworkOrder();
}
public static byte[] Pack(this Int32 value) {
return BitConverter.GetBytes(value).HostToNetworkOrder();
}
public static byte[] Pack(this UInt32 value) {
return BitConverter.GetBytes(value).HostToNetworkOrder();
}
2017-05-17 21:06:16 +00:00
2017-05-09 21:08:39 +00:00
public static byte[] Pack(this Int64 value) {
return BitConverter.GetBytes(value).HostToNetworkOrder();
}
public static byte[] Pack(this UInt64 value) {
return BitConverter.GetBytes(value).HostToNetworkOrder();
}
2017-05-17 21:06:16 +00:00
public static bool IsDivisibleBy(this BigInteger value, BigInteger dividend) {
if(value.IsZero) return false;
if(value.IsOne) return true;
if(value == 2) return value.IsEven;
return (value % dividend).IsZero;
}
public static bool IsProbablePrime(this BigInteger value, int iterations = 5) {
var absValue = BigInteger.Abs(value);
if(absValue == 1) return false;
if(absValue == 2 || absValue == 3 || absValue == 5) return true;
if(absValue.IsEven || absValue.IsDivisibleBy(3) || absValue.IsDivisibleBy(5)) return false;
if(absValue < 25) return true;
for(var i = 0; i < iterations; ++i) {
var rand = Random.NextBigInt(2, absValue - 2);
if(!BigInteger.ModPow(rand, absValue - 1, absValue).IsOne) return false;
}
return true;
}
public static string ToHexString(this BigInteger value) {
return value.ToString("X").ToLower();
}
public static BigInteger HexStringToBigInt(this string value) {
return BigInteger.Parse(value, NumberStyles.HexNumber);
}
2017-05-08 21:06:17 +00:00
}
}