I'm declaring the following constants and printing their values, but when I print they always print in their decimal form. How do I get them to print in their originally defined form?
let binaryInteger = 0b10001
let octalInteger = 0o21
let hexadecimalInteger = 0x11
print("Binary Integer: \(binaryInteger) and in binary \(binaryInteger)")
print("Octal Integer: \(octalInteger) and in octal \(octalInteger)")
print("Hexadecimal Integer: \(hexadecimalInteger) and in hexadecimal \(hexadecimalInteger)")
The output I'd like to see for the first print statement would be:
Binary Integer: 17 and in binary 10001.
What do I need to put in front of the \( to get it to print in binary/octal/hex?
CodePudding user response:
You have to convert the integers to given String representation manually:
print("Binary Integer: \(binaryInteger) and in binary \(String(binaryInteger, radix: 2))")
print("Octal Integer: \(octalInteger) and in octal \(String(octalInteger, radix: 8))")
print("Hexadecimal Integer: \(hexadecimalInteger) and in hexadecimal \(String(hexadecimalInteger, radix: 16))")
Of course, you might also create custom String interpolation to be able to use something like the following:
print("Hexadecimal Integer: \(hexadecimalInteger) and in hexadecimal \(hexadecimalInteger, radix: 16)")
See an example here
CodePudding user response:
Basic answer is given by Silthan, I would also wrap it in the structure, which helps to preserve the original format:
enum Radix: Int {
case binary = 2
case octal = 8
case hexa = 16
var prefix: String {
switch self {
case .binary:
return "0b"
case .octal:
return "0o"
case .hexa:
return "0x"
}
}
}
struct PresentableNumber<T> where T: BinaryInteger & CustomStringConvertible {
let number: T
let radix: Radix
var originalPresentation: String {
return radix.prefix String(number, radix: radix.rawValue)
}
}
extension PresentableNumber: CustomStringConvertible {
var description: String {
return number.description
}
}
This way you can define and print your numbers like this:
let binaryInteger = PresentableNumber(number: 0b10001, radix: .binary)
let octalInteger = PresentableNumber(number: 0o21, radix: .octal)
let hexadecimalInteger = PresentableNumber(number: 0x11, radix: .hexa)
print("Binary Integer: \(binaryInteger) and in binary \(binaryInteger.originalPresentation)")
print("Octal Integer: \(octalInteger) and in octal \(octalInteger.originalPresentation)")
print("Hexadecimal Integer: \(hexadecimalInteger) and in hexadecimal \(hexadecimalInteger.originalPresentation)")
The output:
Binary Integer: 17 and in binary 0b10001
Octal Integer: 17 and in octal 0o21
Hexadecimal Integer: 17 and in hexadecimal 0x11