Extension methods for getting upper and lower 4 bits in a byte

This commit is contained in:
Chris Cameron
2018-03-23 11:59:47 -04:00
parent b00ee4dccb
commit 6b23238162
2 changed files with 60 additions and 40 deletions

View File

@@ -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());
}
}
}

View File

@@ -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);
}
}
}