开发者

Converting NSString to NSDAta

in my project i want to convert NSString value to NSdata without encoding, i.e i am using

NSData* aData = [[NSData alloc] initWithData:[[self getStringValue] dataUsingEncoding:NSUTF8StringEncoding]];

when i am using this the string val开发者_JS百科ue is encoded but i want the same string value without encoding, How can i get this

Thank You


You will always need to choose an encoding of some type. I always recommend NSUTF8StringEncoding. But if you only need the raw character bytes stored and not UTF8 encoding, these are your best options.

// for latin/english only characters
NSData* aData = [self dataUsingEncoding:NSACSIIStringEncoding];

// for international characters
NSData* aData = [self dataUsingEncoding:NSUnicodeStringEncoding]; 


You need an encoding otherwise it won't work. It needs to know what format the string is stored in. It needs to know what format the bytes are stored in. However you should probably be using the NSACSIIStringEncoding.


To convert the string as it is, use the following code:

-(NSData*)getDataFromString:(NSString*)theString
{
    NSMutableData *mData = [NSMutableData data];
    unsigned value;
    NSScanner *scanner = [NSScanner scannerWithString:theString];
    while(![scanner isAtEnd]) {
        [scanner scanHexInt:&value];
        value = htonl(value);
        [mData appendBytes:&value length:sizeof(value)];
    }

    return [NSData dataWithData:mData];
}

And to call this function:

NSData *data = [self getDataFromString:@"Your_String"];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜