anshuman mishra
anshuman mishra

Reputation: 39

How to convert NSString to HEX String in Objective-C?

I have a NSString with string like "hello".

Now I want to convert the string into another NSString object which shows a hex string. How to do that ?

Upvotes: 1

Views: 8963

Answers (1)

Dirk-Willem van Gulik
Dirk-Willem van Gulik

Reputation: 7704

Hmm - apart from the obvious which can be found elsewhere - how about something like:

    NSString * str = @"Hello World";

    NSString * hexStr = [NSString stringWithFormat:@"%@",
                         [NSData dataWithBytes:[str cStringUsingEncoding:NSUTF8StringEncoding] 
                                        length:strlen([str cStringUsingEncoding:NSUTF8StringEncoding])]];

    for(NSString * toRemove in [NSArray arrayWithObjects:@"<", @">", @" ", nil]) 
        hexStr = [hexStr stringByReplacingOccurrencesOfString:toRemove withString:@""];

    NSLog(@"%@", hexStr);

which should give an output like

    48656c6c6f20576f726c64

Optimising this is left as an exercise to the reader :) :)

Upvotes: 6

Related Questions