Swift——How to output a number in a certain base system in another base system (such as printing decimal output into hexadecimal, and printing octal into binary)

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.

Use the built-in calculator for hexadecimal calculations

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 Stringthe 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:

  1. Here ais the source value, you can also directly write a number here.
  2. radix:The latter is the size of the target system, which supports 2~36, that is, from binary system to 36 system.
  3. 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:

Convert decimal to 32 code

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

  1. Adding in front of the number 0bmeans binary, such as 0b1011;
  2. Add in front of the number to 0oindicate octal, such as 0o240;
  3. Add in front of the number to 0xindicate hexadecimal, for example 0x12F(both uppercase and lowercase are acceptable here F);
  4. Do not add anything before the number to indicate decimal, eg 123.

Hope to help those in need~

Guess you like

Origin blog.csdn.net/qq_33919450/article/details/131161069