Last active
October 3, 2019 19:08
-
-
Save SachinR90/13bbd53e734b5ccdad52fb1f3710bdae to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Swift 4+ | |
import Foundation | |
///given formula for representing bits in in number | |
/// bits[index]*(-2)^index | |
func getNumber(from bits:[Int]) -> Int{ | |
var number = 0 | |
for (index, value) in bits.enumerated(){ | |
number = number + value * Int(powf(-2, Float(index))) | |
} | |
return number | |
} | |
///ceil to move forward and abs to get number from bit by reversing the bits representation formula | |
func getBits(for number:Int) -> [Int]{ | |
var tempNumber = number | |
var bits:[Int] = [] | |
while tempNumber != 0 { | |
let remainder = abs(tempNumber % 2) // remove negative | |
bits.append(remainder) | |
tempNumber = Int((Float(tempNumber) / -2).rounded(.up)) // ceil(round-upwards) | |
} | |
return bits | |
} | |
///test | |
print(getNumber(from:[1,0,0,1,1,1])) | |
print(getNumber(from:[0,0,1])) | |
print(getNumber(from:[1,0,0,0,1,1])) | |
print("\n") // :-p | |
print(getBits(for: 22)) | |
print(getBits(for: 11)) | |
print(getBits(for: -5)) | |
print(getBits(for: -4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment