Recently, I need to read some old documents. In the old documents, the memory address is in octal instead of hexadecimal, so I need to write a small tool to convert. Although the Mac built-in calculator can do it, but it is troublesome when there are too many.
At first, I want to write 12 conversion functions. Although some functions can be re-used, it is still quite laborious. So I looked for a simple method. Finally I found the String
type has a particularly magical method, like:
String(a, radix: 16, uppercase: true)
The meaning of each parameter is as follows:
a
here is the source value, you can also write a number directly here.radix:
is followed by the size of the target base, which supports 2~36, meaning from 2 to 36 base.uppercase:
is not required. It is used to capitalize the letters in some binary output.For example, the following code converts decimal to 32 base and capitalizes the letters in the output:
If you want to change the base of your input numbers, Swift supports 4 natively supported bases:
0b
in front of the number to indicate binary, such as 0b1011
;0o
in front of the number to indicate octal, such as 0o240
;0x
in front of the number to indicate hexadecimal, such as 0x12F
(the F
here can be uppercase or lowercase);123
.I hope these will help someone in need~