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.

キーボードからの入力を16進数で解釈(utf8で解釈も参考)

Last updated at Posted at 2022-07-17

事前準備

extension String {
    func splitInto(_ length: Int) -> [String] {
        var str = self
        for i in 0 ..< (str.count - 1) / max(length, 1) {
            str.insert(",", at: str.index(str.startIndex, offsetBy: (i + 1) * max(length, 1) + i))
        }
        return str.components(separatedBy: ",")
    }
}

入力された内容を16進数と解釈

   func send(text1: String) { 
        // 16進数キーボード前提
        let text2 = text1.splitInto(2) // [String]
        let text3 = text2.map { UInt8($0, radix: 16)! }  //[UInt8]
        let data1 = Data(text3) // [Data.Element]

     //ラベルに表示
        label1.text = String(data1[0], radix: 16) // 16進数
        label2.text = String(data1[1], radix: 16) // 16進数
        label3.text = String(data1[2], radix: 16) // 16進数
    }

入力された内容をそのままutf8で解釈

    func send(text: String) {
        // ASCIIキーボード前提
        let utf8 = text.data(using: .utf8)! // Data

     //ラベルに表示
        label4.text = String(utf8[0],radix: 16) // utf8
        label5.text = String(utf8[1],radix: 16) // utf8
        label6.text = String(utf8[2],radix: 16) // utf8
    }

###参考

Swift 3 で16進数文字列と整数の相互変換 - Qiita
https://qiita.com/y13i/items/9af41a1cb507a4b388e0

【Swift5】Data・UInt8のextension備忘録 - Qiita
https://qiita.com/haru15komekome/items/c8d9c3a1a11f0813acdb

【Swift】Data型によるUIntについて
https://zenn.dev/masakunn/articles/c23f64c22f330c

How do I convert UInt8 to Data? | Apple Developer Forums
https://developer.apple.com/forums/thread/119114

//UInt8 to Data
let value: UInt8 = 123
let data = Data([value])

//Data to UInt8
let originalValue = data[0]
print(originalValue) //->123

//[UInt8] to Data
let arrValue: [UInt8] = [123, 234]
let arrData = Data(arrValue)

//Data to [UInt8]
let originalValues = Array(arrData)
print(originalValues) //->[123,234]

//Data to String?
let string = String(data: value, encoding : .utf8)  //String?

//Data to String
if let string = String(data: value, encoding : .utf8) {
...
} else {
...
}    //String

UInt8の16進数を2桁表示したい
(何も意識せずに処理すると、先頭が0の場合、1桁だけになってしまう)

【Swift入門】数値を文字列(String)にformatする方法 | 侍エンジニアブログ
https://www.sejuku.net/blog/34872

String(format: "%02d", i)
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?