diff --git a/String And Int Operation/README.md b/String And Int Operation/README.md new file mode 100644 index 000000000..54078f7ca --- /dev/null +++ b/String And Int Operation/README.md @@ -0,0 +1,39 @@ +# String And Int Operations +The importance of various number like binary numbers, hexadecimals, ASCII values are well known. + +Hence, this file aims to simply and aid in the process of conversion to required result within a tap of few buttons by the help of extensions. + +## Binary Numbers +A base-2 numerical system where an integer is defined using only 1's and 0's +Example : 13 in binary is 1101 + +## Hexadecimal Numbers +A system of representation of numbers where the radix present is 16 i.e. the numbers used in this system range from 0...9 & A,B,C,D,E,F. +Example : 10 in hexadecimal is a + +## ASCII +A method adapted that represents characters as numbers +Example : 'a'(lowercase) in terms of ASCII code is 97 + +## Implementation +```swift +let value = "10".intToHex // returns "10" as Hexadecimal +print(value) // prints "a" +``` + +```swift +let value = "A".ascii // returns "A" as Ascii value +print(value) // prints 65 +``` + +```swift +let value = 13.binString // returns 13 as Binary String +print(value) // prints "1101" +``` + +```swift +let value = 97.intToAscii // returns 97 as a character taking in the integer as ASCII value +print(value) // prints "a" +``` + +*Written for Swift Algorithm Club by Jayant Sogikar* diff --git a/String And Int Operation/String<->Int Operations.swift b/String And Int Operation/String<->Int Operations.swift new file mode 100644 index 000000000..06a63ef11 --- /dev/null +++ b/String And Int Operation/String<->Int Operations.swift @@ -0,0 +1,31 @@ +import UIKit +extension String { + // a -> 10 + var hexToInt : Int{return Int(strtoul(self, nil, 16))} + // a -> 10.0 + var hexToDouble : Double{return Double(strtoul(self, nil, 16))} + // a -> 1010 + var hexToBin : String{return String(hexToInt, radix: 2)} + // 10 -> a + var intToHex : String{ return String(Int(self) ?? 0, radix: 16)} + // 10 -> 1010 + var intToBin : String{return String(Int(self) ?? 0, radix: 2)} + // 1010 -> 10 + var binToInt : Int{return Int(strtoul(self, nil, 2))} + // 1010 -> 10.0 + var binToDouble : Double{return Double(strtoul(self, nil, 2))} + // 1010 -> a + var binToHexa : String{return String(binToInt, radix: 16)} + // a -> 97 + var ascii : Int{return Int(self.unicodeScalars.first!.value)} +} +extension Int { + // 10 -> 1010 + var binString : String{return String(self, radix: 2)} + // 10 -> a + var hexString : String{return String(self, radix: 16)} + // 10 -> 10.0 + var double : Double{ return Double(self)} + // 97 -> a + var intToAscii : String{return String(Character(UnicodeScalar(self)!))} +}