Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate an integer binary representation using Swift?

Tags:

generics

swift

How to create a function accepting any type of Int or Uint in swift (and calculating number of bits needs regarding param type)

like image 469
Luc-Olivier Avatar asked Jul 27 '14 22:07

Luc-Olivier


People also ask

What is binary integer Swift?

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 .

What is the binary representation of the number 15 in Swift?

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.

How do you write binary representation?

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.

What is a integer in Swift?

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.


2 Answers

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
like image 139
Martin R Avatar answered Oct 01 '22 05:10

Martin R


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
}
like image 23
Connor Avatar answered Oct 01 '22 04:10

Connor