Lucas Adam
Lucas Adam

Reputation: 59

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

Upvotes: 3

Views: 1371

Answers (2)

Martin R
Martin R

Reputation: 539975

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

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726929

D8 is the last byte of binary representation of -40. The remaining three bytes are all FFs.

If you are looking for a string that represents only the last byte, you can obtain by first converting your number to unsigned 8-bit integer, and then converting it to hex, like this:

let x = UInt8(bitPattern:Int8(data))
let res = String(format:"%02X", x)

Upvotes: 4

Related Questions