How to use Big5 encoding in Swift on iOS

后端 未结 1 1618
生来不讨喜
生来不讨喜 2021-01-24 05:35

I\'m scanning a QR-Code with chinese characters encoded in Big5. (主页概况)

Is there a chance to get this String decoded correctly in Swift 3?

I found this Objective

相关标签:
1条回答
  • 2021-01-24 05:50

    CFStringEncodings are defined as enumeration values in Swift 3:

    public enum CFStringEncodings : CFIndex {
    
        // ...    
        case big5 /* Big-5 (has variants) */
        // ...    
        case big5_HKSCS_1999 /* Big-5 with Hong Kong special char set supplement*/
        // ...    
    }
    

    so you have to convert

    CFStringEncodings -> CFStringEncoding -> NSStringEncoding -> String.Encoding
    

    Example:

    let cfEnc = CFStringEncodings.big5
    let nsEnc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))
    let big5encoding = String.Encoding(rawValue: nsEnc) // String.Encoding
    

    Then big5encoding can be used for conversion between String and (NS)Data.

    In your case you have a string where each unicode scalar corresponds to a byte of the Big5 encoding. Then the following should work:

    // let code = "\u{00D6}\u{00F7}\u{00D2}\u{00B3}\u{00B8}\u{00C5}\u{00BF}\u{00F6}"
    let bytes = code.unicodeScalars.map { UInt8(truncatingBitPattern: $0.value) }
    if let result = String(bytes: bytes, encoding: big5encoding) {
        print(result)
    }
    

    Alternatively, using the fact that the ISO Latin 1 encoding maps the Unicode code points U+0000 .. U+00FF to the bytes 0x00 .. 0xFF:

    if let data = code.data(using: .isoLatin1),
        let result = String(data: data, encoding: big5encoding) {
        print(result)
    }
    
    0 讨论(0)
提交回复
热议问题