From 1791f82605ad48a1ecdedff316ed9c309058c2bc Mon Sep 17 00:00:00 2001 From: Peter Dettman Date: Tue, 7 Jun 2022 16:29:27 +0700 Subject: Add Highest/LowestOneBit methods --- crypto/src/util/Integers.cs | 27 +++++++++++++++++++++++++++ crypto/src/util/Longs.cs | 28 ++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) (limited to 'crypto/src') diff --git a/crypto/src/util/Integers.cs b/crypto/src/util/Integers.cs index efa437e17..00fb957aa 100644 --- a/crypto/src/util/Integers.cs +++ b/crypto/src/util/Integers.cs @@ -13,6 +13,33 @@ namespace Org.BouncyCastle.Utilities 0x1F, 0x00, 0x1B, 0x01, 0x1C, 0x0D, 0x17, 0x02, 0x1D, 0x15, 0x13, 0x0E, 0x18, 0x10, 0x03, 0x07, 0x1E, 0x1A, 0x0C, 0x16, 0x14, 0x12, 0x0F, 0x06, 0x19, 0x0B, 0x11, 0x05, 0x0A, 0x04, 0x09, 0x08 }; + public static int HighestOneBit(int i) + { + return (int)HighestOneBit((uint)i); + } + + [CLSCompliantAttribute(false)] + public static uint HighestOneBit(uint i) + { + i |= i >> 1; + i |= i >> 2; + i |= i >> 4; + i |= i >> 8; + i |= i >> 16; + return i - (i >> 1); + } + + public static int LowestOneBit(int i) + { + return i & -i; + } + + [CLSCompliantAttribute(false)] + public static uint LowestOneBit(uint i) + { + return (uint)LowestOneBit((int)i); + } + public static int NumberOfLeadingZeros(int i) { if (i <= 0) diff --git a/crypto/src/util/Longs.cs b/crypto/src/util/Longs.cs index 4d675bdba..a2d7dde0f 100644 --- a/crypto/src/util/Longs.cs +++ b/crypto/src/util/Longs.cs @@ -15,6 +15,34 @@ namespace Org.BouncyCastle.Utilities 0x3E, 0x33, 0x05, 0x19, 0x24, 0x27, 0x20, 0x2E, 0x3C, 0x2C, 0x2A, 0x14, 0x16, 0x39, 0x10, 0x09, 0x32, 0x18, 0x23, 0x1F, 0x3B, 0x13, 0x38, 0x0F, 0x31, 0x1E, 0x12, 0x0E, 0x1D, 0x0D, 0x0C, 0x0B }; + public static long HighestOneBit(long i) + { + return (long)HighestOneBit((ulong)i); + } + + [CLSCompliantAttribute(false)] + public static ulong HighestOneBit(ulong i) + { + i |= i >> 1; + i |= i >> 2; + i |= i >> 4; + i |= i >> 8; + i |= i >> 16; + i |= i >> 32; + return i - (i >> 1); + } + + public static long LowestOneBit(long i) + { + return i & -i; + } + + [CLSCompliantAttribute(false)] + public static ulong LowestOneBit(ulong i) + { + return (ulong)LowestOneBit((long)i); + } + public static int NumberOfLeadingZeros(long i) { int x = (int)(i >> 32), n = 0; -- cgit 1.4.1