Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an Int to Hex String in Swift

In Obj-C I used to convert an unsigned integer n to a hex string with

 NSString *st = [NSString stringWithFormat:@"%2X", n]; 

I tried for a long time to translate this into Swift language, but unsuccessfully.

like image 534
boscarol Avatar asked Jun 15 '14 12:06

boscarol


2 Answers

You can now do:

let n = 14 var st = String(format:"%02X", n) st += " is the hexadecimal representation of \(n)" print(st) 
0E is the hexadecimal representation of 14 

Note: The 2 in this example is the field width and represents the minimum length desired. The 0 tells it to pad the result with leading 0's if necessary. (Without the 0, the result would be padded with leading spaces). Of course, if the result is larger than two characters, the field length will not be clipped to a width of 2; it will expand to whatever length is necessary to display the full result.

This only works if you have Foundation imported (this includes the import of Cocoa or UIKit). This isn't a problem if you're doing iOS or macOS programming.

Use uppercase X if you want A...F and lowercase x if you want a...f:

String(format: "%x %X", 64206, 64206)  // "face FACE" 

If you want to print integer values larger than UInt32.max, add ll (el-el, not eleven) to the format string:

let n = UInt64.max print(String(format: "%llX is hexadecimal for \(n)", n)) 
FFFFFFFFFFFFFFFF is hexadecimal for 18446744073709551615 

Original Answer

You can still use NSString to do this. The format is:

var st = NSString(format:"%2X", n) 

This makes st an NSString, so then things like += do not work. If you want to be able to append to the string with += make st into a String like this:

var st = NSString(format:"%2X", n) as String 

or

var st = String(NSString(format:"%2X", n)) 

or

var st: String = NSString(format:"%2X", n) 

Then you can do:

let n = 123 var st = NSString(format:"%2X", n) as String st += " is the hexadecimal representation of \(n)" // "7B is the hexadecimal representation of 123" 
like image 128
vacawama Avatar answered Sep 20 '22 12:09

vacawama


In Swift there is a specific init method on String for exactly this:

let hex = String(0xF, radix: 16, uppercase: false) println("hex=\(hex)") // Output: f 
like image 22
Rich Avatar answered Sep 19 '22 12:09

Rich