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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With