Recently, due to the need to read older documents, the memory addresses in the old documents are in octal instead of hexadecimal, so I need to write a small tool to convert the base. Although the built-in calculator is fine, it is troublesome if there are too many.
At the beginning, I wanted to work hard to write twelve conversion functions. Although some functions can be used, it is still quite laborious. So I looked for a simple method, and found that String
the type has a particularly magical method, which is to use the following code to directly get the converted string:
String(a, radix: 16, uppercase: true)
The meaning of each parameter is as follows:
- Here
a
is the source value, you can also directly write a number here. radix:
The latter is the size of the target system, which supports 2~36, that is, from binary system to 36 system.uppercase:
This parameter is not necessary, it is to capitalize the letters of some base output.
For example, the following code converts decimal to 32 and capitalizes the letters in the output:
If you want to change the base of the input number, Swift supports 4 natively supported bases:
- Adding in front of the number
0b
means binary, such as0b1011
; - Add in front of the number to
0o
indicate octal, such as0o240
; - Add in front of the number to
0x
indicate hexadecimal, for example0x12F
(both uppercase and lowercase are acceptable hereF
); - Do not add anything before the number to indicate decimal, eg
123
.
Hope to help those in need~