どうも、ちょげ(@chogetarou)です。
Stringの文字列をバイト配列に変換する方法を紹介します。
方法
Stringをバイト配列に変換するには、utf8とUInt8を使います。
まず、文字列をutf8でUTF8Viewにします。
そして、UTF8ViewをUInt8の配列にします。
let bytes = str.utf8
let byteArray = [UInt8](bytes)
上記の[UInt8](bytes)は、文字列のバイト配列を返します。
使用例
let greeting = "Hello,Swift"
let bytes = greeting.utf8
let byteArray = [UInt8](bytes)
print(byteArray) //[72, 101, 108, 108, 111, 44, 83, 119, 105, 102, 116]
オススメの記事
コメント