Skip to content

Commit 3d2a2a8

Browse files
committed
Add a way to readSignedBits
1 parent 2a72a1c commit 3d2a2a8

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

Sources/BinaryKit/Binary.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,3 +327,12 @@ public struct Binary {
327327
bytesStore.append(contentsOf: int.bytes)
328328
}
329329
}
330+
331+
332+
extension Binary {
333+
mutating func readSignedBits(_ quantity: UInt8) throws -> Int {
334+
let multiplicationFactor = (try readBit() == 1) ? -1 : 1
335+
let value = try readBits(quantity - 1)
336+
return value * multiplicationFactor
337+
}
338+
}

Tests/BinaryKitTests/BinaryKitTests.swift

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,18 @@ final class BinaryKitTests: XCTestCase {
314314
XCTAssertEqual(try bin.readBits(13), 0x11ff)
315315
}
316316

317+
func testSignedBits() {
318+
var binary = Binary(bytes: [0xFF, 0x7F, 0x00, 0xFF, 0x77, 0xFF, 0xFF])
319+
XCTAssertEqual(try binary.readSignedBits(8), -127)
320+
XCTAssertEqual(try binary.readSignedBits(8), 127)
321+
XCTAssertEqual(try binary.readSignedBits(8), 0)
322+
XCTAssertEqual(try binary.readSignedBits(4), -7)
323+
XCTAssertEqual(try binary.readSignedBits(4), -7)
324+
XCTAssertEqual(try binary.readSignedBits(4), 7)
325+
XCTAssertEqual(try binary.readSignedBits(4), 7)
326+
XCTAssertEqual(try binary.readSignedBits(16), -32767)
327+
}
328+
317329
// MARK: -
318330

319331
static var allTests = [

0 commit comments

Comments
 (0)