Converting Hex String to NSData in Swift

后端 未结 11 1254
一生所求
一生所求 2020-11-27 05:22

I got the code to convert String to HEX-String in objective-C.

- (NSString *) CreateDataWithHexString:(NSString*)inputString
{
NSUInteger inLength = [inputSt         


        
11条回答
  •  隐瞒了意图╮
    2020-11-27 06:03

    Here's a simple solution I settled on:

    extension NSData {
        public convenience init(hexString: String) {
            var index = hexString.startIndex
            var bytes: [UInt8] = []
            repeat {
                bytes.append(hexString[index...index.advancedBy(1)].withCString {
                    return UInt8(strtoul($0, nil, 16))
                })
    
                index = index.advancedBy(2)
            } while index.distanceTo(hexString.endIndex) != 0
    
            self.init(bytes: &bytes, length: bytes.count)
        }
    }
    

    Usage:

    let data = NSData(hexString: "b8dfb080bc33fb564249e34252bf143d88fc018f")
    

    Output:

    print(data)
    >>> 
    

    Update 6/29/2016

    I updated the initializer to handle malformed data (i.e., invalid characters or odd number of characters).

    public convenience init?(hexString: String, force: Bool) {
        let characterSet = NSCharacterSet(charactersInString: "0123456789abcdefABCDEF")
        for scalar in hexString.unicodeScalars {
            if characterSet.characterIsMember(UInt16(scalar.value)) {
                hexString.append(scalar)
            }
            else if !force {
                return nil
            }
        }
    
        if hexString.characters.count % 2 == 1 {
            if force {
                hexString = "0" + hexString
            }
            else {
                return nil
            }
        }
    
        var index = hexString.startIndex
        var bytes: [UInt8] = []
        repeat {
            bytes.append(hexString[index...index.advancedBy(1)].withCString {
                return UInt8(strtoul($0, nil, 16))
                })
    
            index = index.advancedBy(2)
        } while index.distanceTo(hexString.endIndex) != 0
    
        self.init(bytes: &bytes, length: bytes.count)
    }
    

提交回复
热议问题