15860 # strtoul() Function- Swift

I'm trying to create a swift iOS program that converts a number into dec, bin, and hex numbers. I've come across the strtoul function, but don't quite understand how to use it, would someone be able to explain it? Thanks!

The method strtoul is pretty simple to use. You will need also to use String(radix:()) to convert it to the other direction. You can create an extension to convert from hexaToDecimal or from binaryToDecimal as follow:

```extension Int { var toBinary: String { return String(self, radix: 2) } var toHexa: String { return String(self, radix: 16) } } ```

Usage strtoul()

```extension String { var hexaToDecimal: Int { return Int(strtoul(self, nil, 16)) } var hexaToBinary: String { return hexaToDecimal.toBinary } var binaryToDecimal: Int { return Int(strtoul(self, nil, 2)) } var binaryToHexa: String { return binaryToDecimal.toHexa } } ```

Testing

```let myBinFromInt = 255.toBinary // "11111111" let myhexaFromInt = 255.toHexa // "ff" let myIntFromHexa = "ff".hexaToDecimal // 255 let myBinFromHexa = "ff".hexaToBinary // "11111111" let myIntFromBin = "11111111".binaryToDecimal // 255 let myHexaFromBin = "11111111".binaryToHexa // "ff" ```

The strtoul() function converts the string in str to an unsigned long value. The conversion is done according to the given base, which must be between 2 and 36 inclusive, or be the special value 0.

Really it sounds like you want to use NSString

From what it sounds like, you want to convert an unsigned integer to decimal, hex and binary.

For example, if you had an integer `n`:

```var st = NSString(format:"%2X", n) ```

would convert the integer to hexadecimal and store it in the variable `st`.

```//NSString(format:"%2X", 10) would give you 'A' as 10 is A in hex //NSString(format:"%2X", 17) would give you 11 as 17 is 11 in hex ```

Binary:

```var st = NSString(format:"%u", n) ```

Decimal (2 decimal places)

```var st = NSString(format:"%.02f", n) ```