@@ -722,13 +722,17 @@ extension BigInt: IntegerNumber,
722
722
/// This is a signed type
723
723
public static let isSigned : Bool = true
724
724
725
- /// Returns the number of bits used to represent this `BigInt`.
725
+ /// Returns the number of bits used to represent this `BigInt`. This consists of the
726
+ /// words for representing the absolute value and one extra bit for representing the sign.
726
727
public var bitWidth : Int {
727
- return self . uwords. count * UInt32. bitWidth
728
+ return ( self . uwords. count * UInt32. bitWidth) + 1
728
729
}
729
730
730
731
/// Returns the number of trailing zero bits in the representation of this `BigInt`.
731
732
public var trailingZeroBitCount : Int {
733
+ guard !self . isZero else {
734
+ return self . bitWidth
735
+ }
732
736
var i = 0
733
737
while i < self . uwords. count && self . uwords [ i] == 0 {
734
738
i += 1
@@ -738,9 +742,8 @@ extension BigInt: IntegerNumber,
738
742
}
739
743
740
744
/// Returns the words in the binary representation of the magnitude of this number in the
741
- /// format expected by Swift 4.
742
- /// IMPORTANT: This might not return the expected result for negative numbers. Need to
743
- /// figure out the exact spec first.
745
+ /// format expected by Swift 4, i.e. using the two-complement of the representation for
746
+ /// negative numbers.
744
747
public var words : [ UInt ] {
745
748
var res = [ UInt] ( )
746
749
res. reserveCapacity ( ( self . uwords. count + 1 ) / 2 )
@@ -752,6 +755,17 @@ extension BigInt: IntegerNumber,
752
755
i += 1
753
756
res. append ( current | next)
754
757
}
758
+ res. append ( 0 )
759
+ if self . negative {
760
+ var addOne = true
761
+ for i in res. indices {
762
+ if addOne {
763
+ ( res [ i] , addOne) = ( ~ res[ i] ) . addingReportingOverflow ( 1 )
764
+ } else {
765
+ res [ i] = ~ res[ i]
766
+ }
767
+ }
768
+ }
755
769
return res
756
770
}
757
771
@@ -839,7 +853,7 @@ extension BigInt: IntegerNumber,
839
853
}
840
854
841
855
public init ( _ value: UInt ) {
842
- self . init ( Int64 ( value) )
856
+ self . init ( UInt64 ( value) )
843
857
}
844
858
845
859
public init ( _ value: UInt8 ) {
0 commit comments