0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Swift でバイト配列を扱う

Last updated at Posted at 2022-08-18

Swift で Byte 型を扱いたいときは UInt8 型を用います。
つまり、バイト配列は [UInt8] 型になります。
iPhone の NFC リーダーを使ってマイナンバーカードと APDU コマンドで対話をしたくてバイト配列を扱っていたのですが、その時に実装した Extension たちを紹介します。
Swift でバイト配列を扱う機会自体あまりないと思いますが、参考にしていただければ幸いです。

Byte 型の定義

UInt8 型のままバイト配列を扱っても問題ないのですが、直感的に分かりやすくするために Byte 型という UInt8 の別名を定義しています。

Byte+Extension.swift
public typealias Byte = UInt8

Byte の Extension

Byte+Extension.swift
extension Byte {
    
    // 16進数文字列に変換
    func toHexString() -> String {
        var hex = String(self, radix: 16).uppercased()
        if hex.count == 1 {
            hex = "0" + hex
        }
        return hex
    }
    
    // 2進数文字列に変換
    func toBinaryString() -> String {
        var binary = String(self, radix: 2)
        if binary.count < 8 {
            let i = 8 - binary.count
            for _ in 0 ..< i {
                binary = "0" + binary
            }
        }
        return binary
    }
    
}

Data の Extension

Data+Extension.swift
extension Data {
    
    // Data をバイト配列文字列に変換
    func toByteArrayString() -> String {
        let byteArray = [Byte](self)
        var byteArrayString = ""
        let size = byteArray.count
        var i = 0
        for byte in byteArray {
            i+=1
            var hex = byte.toHexString()
            hex = hex.uppercased()
            if size == i {
                byteArrayString += hex
            } else {
                byteArrayString += hex + " "
            }
        }
        return byteArrayString
    }

}

なお、Data と Byte 配列の相互変換は非常に簡単に行えます。

let data = Data(bytes: bytes) // Byte 配列 → Data
let bytes = [Byte](data) // Data → Byte 配列

使用例

// テストデータ
let bytes: [Byte] = [0x00, 0x01, 0xFE, 0xFF]
let data = Data(bytes: bytes)

print(bytes[2].toHexString())
print(bytes[2].toBinaryString())
print(data.toBytesString())

結果

FE
11111110
00 01 FE FF
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?