How to Convert Hex Number to Bin in Swift

Convert between Decimal, Binary and Hexadecimal in Swift

Both String and Int have initializers which take a radix (base). Combining those, you can achieve all of the conversions:

// Decimal to binary
let d1 = 21
let b1 = String(d1, radix: 2)
print(b1) // "10101"

// Binary to decimal
let b2 = "10110"
let d2 = Int(b2, radix: 2)!
print(d2) // 22

// Decimal to hexadecimal
let d3 = 61
let h1 = String(d3, radix: 16)
print(h1) // "3d"

// Hexadecimal to decimal
let h2 = "a3"
let d4 = Int(h2, radix: 16)!
print(d4) // 163

// Binary to hexadecimal
let b3 = "10101011"
let h3 = String(Int(b3, radix: 2)!, radix: 16)
print(h3) // "ab"

// Hexadecimal to binary
let h4 = "face"
let b4 = String(Int(h4, radix: 16)!, radix: 2)
print(b4) // "1111101011001110"

How to convert hex number to bin in Swift?

You can use NSScanner() from the Foundation framework:

let scanner = NSScanner(string: str)
var result : UInt32 = 0
if scanner.scanHexInt(&result) {
println(result) // 37331519
}

Or the BSD library function strtoul()

let num = strtoul(str, nil, 16)
println(num) // 37331519

As of Swift 2 (Xcode 7), all integer types have an

public init?(_ text: String, radix: Int = default)

initializer, so that a pure Swift solution is available:

let str = "239A23F"
let num = Int(str, radix: 16)

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
}

How to convert a decimal number to binary in Swift?

You can convert the decimal value to a human-readable binary representation using the String initializer that takes a radix parameter:

let num = 22
let str = String(num, radix: 2)
print(str) // prints "10110"

If you wanted to, you could also pad it with any number of zeroes pretty easily as well:

Swift 5

func pad(string : String, toSize: Int) -> String {
var padded = string
for _ in 0..<(toSize - string.count) {
padded = "0" + padded
}
return padded
}

let num = 22
let str = String(num, radix: 2)
print(str) // 10110
pad(string: str, toSize: 8) // 00010110

Convert Hexa to Decimal in Swift

FF 88 is the hexadecimal representation of the 16-bit signed integer
-120. You can create an unsigned integer first and then convert it
to the signed counterpart with the same bit pattern:

let h3 = "FF88"
let u3 = UInt16(h3, radix: 16)! // 65416
let s3 = Int16(bitPattern: u3) // -120

How to convert an Int to Hex String in Swift

You can now do:

let n = 14
var st = String(format:"%02X", n)
st += " is the hexadecimal representation of \(n)"
print(st)
0E is the hexadecimal representation of 14

Note: The 2 in this example is the field width and represents the minimum length desired. The 0 tells it to pad the result with leading 0's if necessary. (Without the 0, the result would be padded with leading spaces). Of course, if the result is larger than two characters, the field length will not be clipped to a width of 2; it will expand to whatever length is necessary to display the full result.

This only works if you have Foundation imported (this includes the import of Cocoa or UIKit). This isn't a problem if you're doing iOS or macOS programming.

Use uppercase X if you want A...F and lowercase x if you want a...f:

String(format: "%x %X", 64206, 64206)  // "face FACE"

If you want to print integer values larger than UInt32.max, add ll (el-el, not eleven) to the format string:

let n = UInt64.max
print(String(format: "%llX is hexadecimal for \(n)", n))
FFFFFFFFFFFFFFFF is hexadecimal for 18446744073709551615

Original Answer

You can still use NSString to do this. The format is:

var st = NSString(format:"%2X", n)

This makes st an NSString, so then things like += do not work. If you want to be able to append to the string with += make st into a String like this:

var st = NSString(format:"%2X", n) as String

or

var st = String(NSString(format:"%2X", n))

or

var st: String = NSString(format:"%2X", n)

Then you can do:

let n = 123
var st = NSString(format:"%2X", n) as String
st += " is the hexadecimal representation of \(n)"
// "7B is the hexadecimal representation of 123"

How to convert Hex to decimal in Swift 3? (self written code without third-party library and Foundation)

It should be the same, you just need to change what is inside the ‘for’ loop. So something like this would work:

result = result * 16 + numValue

where ‘numValue’ is the decimal value of ‘num’, so it is 10 for A, 11 for B, ... , 15 for F.

Hexadecimal (Long string)l to Binary

You can do this by converting each character to a 4-digit binary value and then concatenating the binary string values:

let hexString = "3c1878900216d211aa9e0924"

let binary = hexString.compactMap { Int(String($0), radix: 16) }
.map { ("000" + String($0, radix: 2)).suffix(4) }
.joined()
print(binary)

Output:

001111000001100001111000100100000000001000010110110100100001000110101010100111100000100100100100


Related Topics



Leave a reply



Submit