Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Convert Integer to 2 character Hex String

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

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

hex = "0"

How can I format String to result in always 2 characters, in this case I would want

hex = "00"

like image 993
Ian Clay Avatar asked Sep 16 '15 12:09

Ian Clay


1 Answers

You can add a padding 0 before the formatter 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
like image 55
Eric Aya Avatar answered Sep 19 '22 22:09

Eric Aya