Swift中的二进制到十六进制 [英] Binary to hexadecimal in Swift
问题描述
我有一个二进制字符串(例如"00100100"),我希望它以十六进制形式(如"24").
I have a string in binary (for example "00100100"), and I want it in hexadecimal (like "24").
是否编写了一种在Swift中将Binary转换为十六进制的方法?
Is there a method written to convert Binary to Hexadecimal in Swift?
推荐答案
可能的解决方案:
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
}
只要数字适合UInt
(32位或64位,
取决于平台).它使用BSD库函数 strtoul( ),它会根据给定的基数将字符串转换为整数.
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.
对于更大的数字,您必须处理输入 大块地.您可能还添加了输入字符串的 validation .
For larger numbers you have to process the input in chunks. You might also add a validation of the input string.
Swift 3/4的更新:不再需要strtoul
功能.
返回nil
表示无效输入:
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
}
这篇关于Swift中的二进制到十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!