主页 Swift UNIX C Assembly Go Plan 9 Web MCU Research Non-Tech

How to convert number from some base to other base in Swift

2023-06-12 | Swift | #Words: 323

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.

Use the built-in calculator for hexadecimal calculations

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:

  1. a here is the source value, you can also write a number directly here.
  2. radix: is followed by the size of the target base, which supports 2~36, meaning from 2 to 36 base.
  3. The 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:

Code to convert decimal to 32 base

If you want to change the base of your input numbers, Swift supports 4 natively supported bases:

  1. Add 0b in front of the number to indicate binary, such as 0b1011;
  2. Add 0o in front of the number to indicate octal, such as 0o240;
  3. Add 0x in front of the number to indicate hexadecimal, such as 0x12F (the F here can be uppercase or lowercase);
  4. Nothing before the number to indicate decimal, such as 123.

I hope these will help someone in need~