Swift Program to convert Decimal to Hexadecimal

This tutorial will discuss how to write Swift program to convert Decimal to Hexadecimal number.

Decimal numbers are those numbers whose base value is 10. Decimal numbers are also known as base-10 number system which contain 10 numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Here, the position of every digit in the decimal number has weight is a power of 10. For example, (89)10 = 8 x 101 + 9 x 100.

Hexadecimal numbers are those numbers whose base value is 16. Hexadecimal numbers are also known as base-16 number system which contain 16 symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E and F. Here, A, B, C, D, E, and F also represents decimal numbers 10, 11, 12, 13, 14, 15. Here, the position of every digit in the hexadecimal number has weight is a power of 16.

0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 A
11 B
12 C
13 D
14 E

Below is a demonstration of the same −

Input

Suppose our given input is −

Decimal number = 2D


Output

The desired output would be −

Hexadecimal number = 45


To convert the decimal(base-10) to hexadecimal(base-16) number we use String(_:radix:). This method creates a new value from the given string/number and radix.

Syntax

Following is the syntax −

String(value, radix: base)


Here, value is the ASCII representation of a number. Whereas radix is used to convert text into integer value. The default value of radix is 10 and it can be in the range from 2…36.

Example

The following program shows how to convert decimal to Hexadecimal number.

import Foundation
import Glibc

// Decimal number
let deciNumber = 12
print("Decimal Number:", deciNumber)

// Converting decimal number into hexadecimal number
let hexaNumber = String(deciNumber, radix: 16)


Output

Decimal Number: 12

let hexaNumber = String(deciNumber, radix: 16)