Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary to hexadecimal in Swift

Tags:

hex

swift

binary

I have a string in binary (for example "00100100"), and I want it in hexadecimal (like "24").

Is there a method written to convert Binary to Hexadecimal in Swift?

like image 238
Dejan Skledar Avatar asked Oct 19 '25 01:10

Dejan Skledar


1 Answers

A possible solution:

func binToHex(bin : String) -> String {
    // binary to integer:
    let num = bin.withCString { strtoul($0, nil, 2) }
    // integer to hex:
    let hex = String(num, radix: 16, uppercase: true) // (or false)
    return hex
}

This works as long as the numbers fit into the range of UInt (32-bit or 64-bit, depending on the platform). It uses the BSD library function strtoul() which converts a string to an integer according to a given base.

For larger numbers you have to process the input in chunks. You might also add a validation of the input string.

Update for Swift 3/4: The strtoul function is no longer needed. Return nil for invalid input:

func binToHex(_ bin : String) -> String? {
    // binary to integer:
    guard let num = UInt64(bin, radix: 2) else { return nil }
    // integer to hex:
    let hex = String(num, radix: 16, uppercase: true) // (or false)
    return hex
}
like image 97
Martin R Avatar answered Oct 21 '25 15:10

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!