【Swift】Int型 ⇄ 16進数文字列 ⇄ バイト配列(UInt8配列) を相互変換する
はじめに
BLE通信などを実装していると、Write / Read のタイミングでバイト型を扱うと思います。
業務でファームウェアの仕様に合わせ、Int型 ⇄ 16進数文字列 ⇄ バイト配列 で相互変換する必要がありました。
ここら辺は忘れやすいかなと思い、まとめることにしました!
環境
- Xcode12.5
- Swift5
変換していく
今回は、以下のデータを変換していきます。
Int型 | 16進数文字列 | バイト配列(UInt8配列) |
---|---|---|
123456789 | "075BCD15" | [7, 91, 205, 21] |
16進数文字列 -> Byte配列
ごりごり加工していくので、別途 extension に関数を定義しています。
extension String {
func toBytes() -> [UInt8]? {
var hexString = self
if hexString.count % 2 == 1 {
hexString = "0" + hexString
}
var bytes = [UInt8]()
bytes.reserveCapacity(hexString.count / 2)
var index = hexString.startIndex
for _ in 0..<hexString.count / 2 {
let nextIndex = hexString.index(index, offsetBy: 2)
if let byte = UInt8(hexString[index..<nextIndex], radix: 16) {
bytes.append(byte)
} else {
return nil
}
index = nextIndex
}
return bytes
}
}
上の関数を使ってみます。
let hexString = "075BCD15"
let bytes = hexString.toBytes()
print(bytes) // Optional([7, 91, 205, 21])
Byte配列 -> 16進数文字列
0埋めできていないですね。。。
let bytes = Data([7, 91, 205, 21])
let hexString = bytes.map { String(format: "%02hhX", $0) }.joined()
print(hexString) // 75BCD15
Int型 -> 16進数文字列
let integer = 123456789
let hexString = String(format: "%02X", integer)
print(hexString) // 1234567879
16進数文字列 -> Int型
let hexString = "075BCD15"
let integer = Int(hexString, radix: 16)
print(integer) // Optional(123456789)
以上です!
参考にした記事
Author And Source
この問題について(【Swift】Int型 ⇄ 16進数文字列 ⇄ バイト配列(UInt8配列) を相互変換する), 我々は、より多くの情報をここで見つけました https://qiita.com/yusinoue1008/items/702da507199cfee13212著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .