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 5 years have passed since last update.

16進数文字列(NSString)をNSDataに変換する

Posted at

はじめに

 需要があるかどうかは分かりませんが、16進数文字列をNSData化するコードを参考URLをほぼ丸パクリ参考にし、Swift対応にしました。

環境

  • Xcode 7.01
  • Swift

使い方(一例

let hexStr : NSString = "48656c6c6f20576f726c64"
let moji =  NSString.init(data: hexStr.dataFromHexString()!, encoding: NSUTF8StringEncoding)
print(moji)
//-> Hello World

コード

何故かNSStringのextensionになっておりますが、適宜変更する方がよろしいかと思います。

NSStringEX.swift
import Foundation

extension NSString
{
    func dataFromHexString() -> NSData?
    {
        var str = self.stringByReplacingOccurrencesOfString("<", withString: "")
        str = str.stringByReplacingOccurrencesOfString(">", withString: "")
        str = str.stringByReplacingOccurrencesOfString(" ", withString: "")
        
        let nsstr = str as NSString
        
        let chars = nsstr.UTF8String
        var i = 0
        let len = nsstr.length;
        
        let data = NSMutableData(capacity: len/2)
        var byteChars:[CChar] = [0,0]

            var wholeByte :CUnsignedLong
            while (i < len)
            {
                byteChars[0] = chars[i++];
                byteChars[1] = chars[i++];
                wholeByte = strtoul(byteChars, nil, 16);
                data?.appendBytes(&wholeByte, length: 1)
            }
        
        return data;
    }

}

参考URL

stack over flow -NSString (hex) to bytes-
http://stackoverflow.com/questions/2501033/nsstring-hex-to-bytes

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?