Swift Convert an integer to 2 characters. Hex String

I am trying to get a hex value from an integer:

let hex = String(format:"%2X", 0)
print ("hex = \(hex)")

hex = "0"

How can I format a String to always output two characters, in which case I would like to

hex = "00"

+4
source share
1 answer

You can add a space 0 before the format string:

let hex = String(format:"%02X", 0)

Result:

let hex = String(format:"%02X", 0) // 00
let hex = String(format:"%02X", 15) // 0F
let hex = String(format:"%02X", 16) // 10
+11
source

Source: https://habr.com/ru/post/1607647/


All Articles