mirror of
https://github.com/ICDSystems/ICD.Common.Utils.git
synced 2026-02-17 13:45:05 +00:00
Extension methods for getting upper and lower 4 bits in a byte
This commit is contained in:
@@ -39,5 +39,17 @@ namespace ICD.Common.Utils.Tests.Extensions
|
||||
{
|
||||
Assert.AreEqual(expected, value.SetBitOff(index));
|
||||
}
|
||||
|
||||
[TestCase(0xFF, 0x0F)]
|
||||
public void GetLower4BitsTest(byte b, byte expected)
|
||||
{
|
||||
Assert.AreEqual(expected, b.GetLower4Bits());
|
||||
}
|
||||
|
||||
[TestCase(0xFF, 0xF0)]
|
||||
public void GetUpper4BitsTest(byte b, byte expected)
|
||||
{
|
||||
Assert.AreEqual(expected, b.GetUpper4Bits());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,22 +7,20 @@ namespace ICD.Common.Utils.Extensions
|
||||
public static bool GetBit(this byte b, int n)
|
||||
{
|
||||
if (n > 7 || n < 0)
|
||||
throw new ArgumentException();
|
||||
throw new ArgumentOutOfRangeException("n");
|
||||
|
||||
return (b & (1 << n)) == (1 << n);
|
||||
}
|
||||
|
||||
public static byte SetBit(this byte b, int n, bool v)
|
||||
{
|
||||
if (v)
|
||||
return SetBitOn(b, n);
|
||||
return SetBitOff(b, n);
|
||||
return v ? SetBitOn(b, n) : SetBitOff(b, n);
|
||||
}
|
||||
|
||||
public static byte SetBitOn(this byte b, int n)
|
||||
{
|
||||
if (n > 7 || n < 0)
|
||||
throw new ArgumentException();
|
||||
throw new ArgumentOutOfRangeException("n");
|
||||
|
||||
return (byte)(b | (1 << n));
|
||||
}
|
||||
@@ -30,9 +28,19 @@ namespace ICD.Common.Utils.Extensions
|
||||
public static byte SetBitOff(this byte b, int n)
|
||||
{
|
||||
if (n > 7 || n < 0)
|
||||
throw new ArgumentException();
|
||||
throw new ArgumentOutOfRangeException("n");
|
||||
|
||||
return (byte)(b & ~(1 << n));
|
||||
}
|
||||
|
||||
public static byte GetLower4Bits(this byte b)
|
||||
{
|
||||
return (byte)(b & 15);
|
||||
}
|
||||
|
||||
public static byte GetUpper4Bits(this byte b)
|
||||
{
|
||||
return (byte)(b >> 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user