How to create a function accepting any type of Int or Uint in swift (and calculating number of bits needs regarding param type)
An integer type with a binary representation. The BinaryInteger protocol is the basis for all the integer types provided by the standard library. All of the standard library's integer types, such as Int and UInt32 , conform to BinaryInteger .
The binary equivalent of 15 is 1111. That means, the decimal number 15 can be written in the binary system as 1111. Since, we know that the binary number system contains the representation of numbers in combination with 0's and 1's. Based on the counting in the binary system, we can express 15 as 1111 in binary code.
To represent a number in binary, every digit has to be either 0 or 1 (as opposed to decimal numbers where a digit can take any value from 0 to 9). The subscript 2 denotes a binary (i.e., base 2) number.
Integers. Integers are whole numbers with no fractional component, such as 42 and -23 . Integers are either signed (positive, zero, or negative) or unsigned (positive or zero). Swift provides signed and unsigned integers in 8, 16, 32, and 64 bit forms.
String
has constructors
init<T : _SignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default)
init<T : _UnsignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default)
which can be used here:
let num = 100
let str = String(num, radix: 2)
print(str)
// Output: 1100100
Here's a little shorter version. It doesn't add extra leading zeroes though:
func bitRep<T: IntegerArithmeticType>(value: T) -> String {
var n: IntMax = value.toIntMax()
var rep = ""
while(n > 0){
rep += "\(n % 2)"
n = n / 2;
}
return rep
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With