4

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?

1
  • I'd be very surprised, but its not hard to do if you cut up the string into 4-character chunks. Commented Oct 23, 2014 at 13:46

2 Answers 2

8

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks to the anonymous downvoter, who reminded me to update the code for the current Swift :)
What if i want to convert 80 char long string to Hex e.g. "10000000000000000000000000000000000000000000000000000000000000000000000000000001" , it wont allow beyond 64bits.
0
let binaryInteger = 0b1 
// Your binary number
let hexadecimalNum = String(binaryInteger, radix: 16) 
// convert into string format in whatever base you want

For more information

let decimalInteger = 15       // prefix NONE
let binaryInteger = 0b10001   // prefix 0b
let octalInteger = 0o21       // prefix 0o
let hexadecimalInteger = 0x11 // prefix 0x

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.