Swift equivalent to Objective-C FourCharCode single quote literals (e.g. 'TEXT')

后端 未结 7 2530
天命终不由人
天命终不由人 2021-02-20 12:54

I am trying replicate some Objective C cocoa in Swift. All is good until I come across the following:

// Set a new type and creator:
unsigned long type = \'TEXT\         


        
7条回答
  •  [愿得一人]
    2021-02-20 13:40

    Here's a simple function

    func mbcc(foo: String) -> Int
    {
        let chars = foo.utf8
        var result: Int = 0
        for aChar in chars
        {
            result = result << 8 + Int(aChar)
        }
        return result
    }
    
    let a = mbcc("TEXT")
    
    print(String(format: "0x%lx", a)) // Prints 0x54455854
    

    It will work for strings that will fit in an Int. Once they get longer it starts losing digits from the top.

    If you use

    result = result * 256 + Int(aChar)
    

    you should get a crash when the string gets too big instead.

提交回复
热议问题