Skip to content

Commit

Permalink
Fixed #105 - bug in sliceToByte
Browse files Browse the repository at this point in the history
  • Loading branch information
mpilquist committed Jan 17, 2019
1 parent 21e1208 commit 4a467cf
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
4 changes: 2 additions & 2 deletions core/shared/src/main/scala/scodec/bits/BitVector.scala
Original file line number Diff line number Diff line change
Expand Up @@ -770,13 +770,13 @@ sealed abstract class BitVector extends BitwiseOperations[BitVector, Long] with
*/
final def sliceToByte(start: Long, bits: Int, signed: Boolean = true): Byte = {
if (start % 8 != 0) drop(start).sliceToByte(0, bits, signed)
else if (isEmpty) 0.toByte
else if (isEmpty || bits == 0) 0.toByte
else getByte(start, bits, signed)
}

private def getByte(start: Long, bits: Int, signed: Boolean): Byte = {
require(sizeGreaterThanOrEqual(start + bits) && bits >= 0 && bits <= 8)
var result = 0x0ff & getByte(0)
var result = 0x0ff & getByte(start / 8)
if (bits != 0) result = result >>> (8 - bits)
// Sign extend if necessary
if (signed && bits != 8 && ((1 << (bits - 1)) & result) != 0) {
Expand Down
8 changes: 8 additions & 0 deletions core/shared/src/test/scala/scodec/bits/BitVectorTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,14 @@ class BitVectorTest extends BitsSuite {
hex"001122334455".bits.slice(-21, -5) shouldBe hex"".bits
}

test("sliceToByte") {
forAll { (x: BitVector, offset0: Long, sliceSize0: Int) =>
val offset = if (x.nonEmpty) (offset0 % x.size).abs else 0
val sliceSize = (sliceSize0 % 9).abs.min((x.size - offset).toInt)
x.sliceToByte(offset, sliceSize).toInt shouldBe x.drop(offset).take(sliceSize.toLong).toInt()
}
}

test("highByte") {
BitVector.highByte.toBin shouldBe "11111111"
}
Expand Down

0 comments on commit 4a467cf

Please sign in to comment.