Lucas Adam Lucas Adam - 11 days ago 6
Swift Question

Swift 3 : Negative Int to hexadecimal

Hy everyone,

I need to transform a Int to its hexadecimal value.
Example : -40 => D8

I have a working method for positive (or unsigned) Int but it doesn't work as expected with negatives. Here's my code.

class func encodeHex(data:[Int]) -> String {
let hexadecimal = data.reduce("") { (string , element) in
var append = String(element, radix:16 , uppercase : false)
if append.characters.count == 1 {
append = "0" + append
}
return string + append
}
return hexadecimal
}


If I pass -40 I get -28.

Can anyone help ? Thanks :)

Answer

I assume from your existing code that all integers are in the range -128 ... 127. Then this would work:

func encodeHex(data:[Int]) -> String {
    return data.map { String(format: "%02hhX", $0) }.joined()
}

The "%02hhX" format prints the least significant byte of the given integer in base 16 with 2 digits.

Example:

print(encodeHex(data: [40, -40, 127, -128]))
// 28D87F80